Fre*_*ead 4 php dependency-injection illuminate-container laravel-5
简短的说明:我无法使用composer(https://packagist.org/packages/illuminate/container)安装Laravel容器进行方法注入.仅当在对象的构造函数中使用时,注入才有效.例如:
class SomeClass {
function __construct(InjectedClassWorksHere $obj) {}
function someFunction(InjectedClassFailsHere $obj) {}
}
Run Code Online (Sandbox Code Playgroud)
长话故事:我正在考虑重新考虑使用Laravel的一个重大项目,但由于业务压力,我无法投入我想要的时间.为了不让"宝宝带着洗澡水",我正在使用各个Laravel组件来提升旧分支中开发的代码的优雅.在评估Laravel时我最喜欢的一种新技术是依赖注入的概念.我很高兴后来发现我可以使用Laravel项目的外部.我现在有这个工作,一切都很好,除了在线发现的容器的开发版本似乎不支持方法注入.
有没有其他人能够让容器工作并在Laravel项目之外进行方法注入?
我的方法到目前为止......
composer.json
"illuminate/support": "5.0.*@dev",
"illuminate/container": "5.0.*@dev",
Run Code Online (Sandbox Code Playgroud)
应用程序引导代码:
use Illuminate\Container\Container;
$container = new Container();
$container->bind('app', self::$container); //not sure if this is necessary
$dispatcher = $container->make('MyCustomDispatcher');
$dispatcher->call('some URL params to find controller');
Run Code Online (Sandbox Code Playgroud)
有了上面的内容,我可以注入我的控制器的构造函数,但不能注入它们的方法方法.我错过了什么?
完整源代码...(C:\ workspace\LMS> php cmd\test_container.php)
<?php
// This sets up my include path and calls the composer autoloader
require_once "bare_init.php";
use Illuminate\Container\Container;
use Illuminate\Support\ClassLoader;
use Illuminate\Support\Facades\Facade;
// Get a reference to the root of the includes directory
$basePath = dirname(dirname(__FILE__));
ClassLoader::register();
ClassLoader::addDirectories([
$basePath
]);
$container = new Container();
$container->bind('app', $container);
$container->bind('path.base', $basePath);
class One {
public $two;
public $say = 'hi';
function __construct(Two $two) {
$this->two = $two;
}
}
Class Two {
public $some = 'thing';
public function doStuff(One $one) {
return $one->say;
}
}
/* @var $one One */
$one = $container->make(One);
var_dump($one);
print $one->two->doStuff();
Run Code Online (Sandbox Code Playgroud)
当我运行上述内容时,我得到......
C:\workspace\LMS>php cmd\test_container.php
object(One)#9 (2) {
["two"]=>
object(Two)#11 (1) {
["some"]=>
string(5) "thing"
}
["say"]=>
string(2) "hi"
}
PHP Catchable fatal error: Argument 1 passed to Two::doStuff() must be an instance of One, none
given, called in C:\workspace\LMS\cmd\test_container.php on line 41
and defined in C:\workspace\LMS\cmd\test_container.php on line 33
Catchable fatal error: Argument 1 passed to Two::doStuff() must be an instance of One, none
given, called in C:\workspace\LMS\cmd\test_container.php on line 41 and
defined in C:\workspace\LMS\cmd\test_container.php on line 33
Run Code Online (Sandbox Code Playgroud)
或者,一个更基本的例子,说明注入在构造函数中工作但不是方法...
class One {
function __construct(Two $two) {}
public function doStuff(Three $three) {}
}
class Two {}
class Three {}
$one = $container->make(One); // totally fine. Injection works
$one->doStuff(); // Throws Exception. (sad trombone)
Run Code Online (Sandbox Code Playgroud)
只需将实例传递给One
您的电话Two
:
$one = $container->make('One');
var_dump($one);
print $one->two->doStuff($one);
Run Code Online (Sandbox Code Playgroud)
返回...
object(One)#8 (2) {
["two"]=>
object(Two)#10 (1) {
["some"]=>
string(5) "thing"
}
["say"]=>
string(2) "hi"
}
hi
Run Code Online (Sandbox Code Playgroud)
如下所述,在Laravel 5.0中,方法注入仅适用于路由和控制器.所以你也可以把它们拉进你的项目中,并在这个过程中获得更多的Laravel-y.这是如何做:
在composer.json
,需要添加illuminate/routing
和illuminate/events
:
{
"require-dev": {
"illuminate/contracts": "5.0.*@dev",
"illuminate/support": "5.0.*@dev",
"illuminate/container": "5.0.*@dev",
"illuminate/routing": "5.0.*@dev",
"illuminate/events": "5.0.*@dev"
},
"autoload": {
"psr-4": {
"App\\": "app/"
}
},
"minimum-stability": "dev",
"prefer-stable": true
}
Run Code Online (Sandbox Code Playgroud)
在routing.php
,设置Laravel的路由和控制器服务:
/**
* routing.php
*
* Sets up Laravel's routing and controllers
*
* adapted from http://www.gufran.me/post/laravel-components
* and http://www.gufran.me/post/laravel-illuminate-router-package-in-your-application
*/
$basePath = str_finish(dirname(__FILE__), '/app/');
$controllersDirectory = $basePath . 'Controllers';
// Register directories into the autoloader
Illuminate\Support\ClassLoader::register();
Illuminate\Support\ClassLoader::addDirectories($controllersDirectory);
// Instantiate the container
$app = new Illuminate\Container\Container();
$app['env'] = 'production';
$app->bind('app', $app); // optional
$app->bind('path.base', $basePath); // optional
// Register service providers
with (new Illuminate\Events\EventServiceProvider($app))->register();
with (new Illuminate\Routing\RoutingServiceProvider($app))->register();
require $basePath . 'routes.php';
$request = Illuminate\Http\Request::createFromGlobals();
$response = $app['router']->dispatch($request);
$response->send();
Run Code Online (Sandbox Code Playgroud)
在Controllers/One.php
,创建类作为控制器,所以我们可以使用L5的方法注入:
/**
* Controllers/One.php
*/
Class One extends Illuminate\Routing\Controller {
public $some = 'thingOne';
public $two;
public $three;
function __construct(Two $two) {
$this->two = $two;
echo('<pre>');
var_dump ($two);
echo ($two->doStuffWithTwo().'<br><br>');
}
public function doStuff(Three $three) {
var_dump ($three);
return ($three->doStuffWithThree());
}
}
Run Code Online (Sandbox Code Playgroud)
在routes.php
,定义我们的测试路线:
$app['router']->get('/', 'One@dostuff');
Run Code Online (Sandbox Code Playgroud)
最后,在index.php
,启动所有内容并定义我们的类来测试依赖注入:
/**
* index.php
*/
// turn on error reporting
ini_set('display_errors',1);
error_reporting(E_ALL);
require 'vendor/autoload.php';
require 'routing.php';
// the classes we wish to inject
Class Two {
public $some = 'thing Two';
public function doStuffWithTwo() {
return ('Doing stuff with Two');
}
}
Class Three {
public $some = 'thing Three';
public function doStuffWithThree() {
return ('Doing stuff with Three');
}
}
Run Code Online (Sandbox Code Playgroud)
点击index.php,你应该得到这个:
object(Two)#40 (1) {
["some"]=>
string(9) "thing Two"
}
Doing stuff with Two
object(Three)#41 (1) {
["some"]=>
string(11) "thing Three"
}
Doing stuff with Three
Run Code Online (Sandbox Code Playgroud)
一些笔记......
$one->doStuff();
,抛出异常的空参数(因为doStuff
期望一个实例).相反,路由器doStuff
为我们调用并解析IoC容器.