短篇小说: 我无法使用 composer ( https://packagist.org/packages/illuminate/container ) 安装的 Laravel 容器进行方法注入(inject)。注入(inject)仅在对象的构造函数中使用时才有效。例如:
class SomeClass {
function __construct(InjectedClassWorksHere $obj) {}
function someFunction(InjectedClassFailsHere $obj) {}
}
长话短说: 我正在考虑重构一个主要项目以使用 Laravel,但由于业务压力,我无法投入我想要的时间。为了不把“婴儿和洗澡水一起扔掉”,我正在使用单独的 Laravel 组件来提升旧分支中正在开发的代码的优雅。在评估 Laravel 时我最喜欢的新技术之一是依赖注入(inject)的概念。我很高兴后来发现我可以在 Laravel 项目之外使用它。我现在可以正常工作,一切都很好,除了在网上找到的容器的开发版本似乎不支持方法注入(inject)。
有没有其他人能够让容器工作并在 Laravel 项目之外进行方法注入(inject)?
到目前为止我的方法...
Composer .json
"illuminate/support": "5.0.*@dev",
"illuminate/container": "5.0.*@dev",
应用引导代码:
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');
通过上述,我可以注入(inject)我的 Controller 的构造函数,但不能注入(inject)它们的方法。我错过了什么?
完整源代码... (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();
当我运行上面的代码时,我得到...
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
或者,一个更基本的例子,说明注入(inject)在构造函数而不是方法中工作......
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)
最佳答案
只需将 One 的实例传递到您对 Two 的调用中:
$one = $container->make('One');
var_dump($one);
print $one->two->doStuff($one);
返回...
object(One)#8 (2) {
["two"]=>
object(Two)#10 (1) {
["some"]=>
string(5) "thing"
}
["say"]=>
string(2) "hi"
}
hi
如下所述,在 Laravel 5.0 中,方法注入(inject)仅适用于路由和 Controller 。因此,您也可以将它们拉入您的项目,并在此过程中获得更多 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
}
在 routing.php 中,设置 Laravel 的路由和 Controller 服务:
/**
* 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();
在Controllers/One.php中,创建类作为Controller,这样我们就可以使用L5的方法注入(inject):
/**
* 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());
}
}
在routes.php中,定义我们的测试路由:
$app['router']->get('/', 'One@dostuff');
最后,在 index.php 中,启动一切并定义我们的类来测试依赖注入(inject):
/**
* 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');
}
}
点击 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
一些笔记...
$one->doStuff();,并使用会引发异常的空参数(因为 doStuff 需要个实例)。相反,路由器调用 doStuff 并为我们解析 IoC 容器。关于php - 如何在 Laravel 之外使用 Laravel 的 IOC 容器进行方法注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25837941/
我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看rubyzip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
很好奇,就使用rubyonrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提
假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于
出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits
我正在尝试使用ruby和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我
我正在尝试设置一个puppet节点,但rubygems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由rubygems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。