mrsimonbennett / dipr
Dependency Injection For Controller Methods in Laravel
Requires
- php: >=5.4.0
This package is auto-updated.
Last update: 2024-11-29 04:14:50 UTC
README
Dependency Injection for Methods in Laravel Controllers
Enabling you to use the IOC to inject into controllers methods. Why? Well somethings you have a instance of something you only want for one of a controllers methods so does not make sense to inject via the constructor.
Quick Example
public function index( \ACME\Validation\Company $companyValidation)
{ }
#Requirments
- Laravel 4.2
- PHP 5.4
- Changing the Base Controller/Your Controller to Extend from the packages
#Installing
Add To composer.json
{ "require": { "mrsimonbennett/dipr": "dev-master" } }
I recommend you use a BaseController of some sort, if not your controller need to extend Mrsimonbennett\Dipr\Controller
<?php use Mrsimonbennett\Dipr\Controller; class BaseController extends Controller { }
#Usage Example (needs more work)
/** * Class ProcessController * @package Amce\Controllers */ class ProcessController extends \BaseController { /** * @param Request $request */ public function getRequest(Request $request) { return $request->All(); } /** * @param Request $request * @param string $slugFromRouteConfig */ public function getRequestWithURLSlug(Request $request, $slugFromRouteConfig) { } /** * @param User $userFromRouteConfig * @param Request $request * @param string $randomSlugStringFromRouteConfig */ public function getRequestWithModelFromRouter(User $userFromRouteConfig,Request $request, $randomSlugStringFromRouteConfig) { } }
As you can see objects are always first before strings/ints loaded using the router.php
#How It works
- The code looks at the signuture of the method.
- Then it looks at parameters the router is sending
- If the any of the parameters are objects there are stored in a list
- The code them matches the objects in the stored list with the signuture
- If the object in the signuture does not exist the use the App::Make() method is called, which will use the magic of the laravel's IOC to pass you that object (whether it neededs to be created or already exists)
- Anything thats not in the process like slugs and ints are passed to the method last.
If you get stuck you can always use var_dump the func_get_args() and see whats going on