Dependency Injection For Controller Methods in Laravel
88
1
2
Package Data
Maintainer Username: mrsimonbennett
Maintainer Contact: simon@bennett.im (Simon Bennett)
Package Create Date: 2014-05-25
Package Last Update: 2014-08-07
Language: PHP
License: MIT
Last Refreshed: 2024-11-19 03:22:15
Package Statistics
Total Downloads: 88
Monthly Downloads: 0
Daily Downloads: 0
Total Stars: 1
Total Watchers: 2
Total Forks: 0
Total Open Issues: 1

Dipr

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

  1. The code looks at the signuture of the method.
  2. Then it looks at parameters the router is sending
  3. If the any of the parameters are objects there are stored in a list
  4. The code them matches the objects in the stored list with the signuture
  5. 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)
  6. 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