While looking at the Laravel source, I noticed a lot of stuff like this:
A controller class:
class Controller extends BaseController
{
use AuthorizesRequests, AuthorizesResources, DispatchesJobs, ValidatesRequests;
}
One of its component traits:
trait AuthorizesRequests {
/**
* Authorize a given action against a set of arguments.
*
* @param mixed $ability
* @param mixed|array $arguments
*
* @return \Illuminate\Auth\Access\Response
*
* @throws \Illuminate\Auth\Access\AuthorizationException
*/
public function authorize($ability, $arguments = []) {
list($ability, $arguments) = $this->parseAbilityAndArguments($ability, $arguments);
return app(Gate::class)->authorize($ability, $arguments);
}
// ...
}
I have a couple of questions about this:
- Does this pattern (abstracting re-usable functionality into traits) have a name?
- Is this pattern used to good effect in any other projects?
- If a trait requires dependencies, is there a best-practise way to inject them, instead of using a service locator (like
app()
, in this case)?
I'm considering using this approach in my code to share some general functionality between a couple of my classes - I'm considering creating a ChecksBarcodes
trait, which will work with a repository of stock information, and sharing that trait between a few similar but unrelated product management process classes, which all need to check barcodes.
Aucun commentaire:
Enregistrer un commentaire