php - laravel如何通过容器获取自定义类并且传递参数?
滿天的星座
滿天的星座 2017-05-16 12:59:28
0
3
687

现在公司业务需要在C层的基础上添加一个services层,代替controller进行一部分业务处理.
所以我在app目录下新建了一个Services文件夹,然后在c层控制器里调用:
$services = App::make('要调用的service的完整类名');
这样虽然可以获取到services文件夹里指定的类了,但是如果这个类的构造函数需要参数则完全无法传递.
我尝试过这样写:
controller层:

public function test(){
    $services = \App::make('App\Services\Servicetest',[1,2]);
    $services->test();
}

在app/services目录下的Servicetest.php里这样写:

public function __construct($a, $b){
    echo $a;
    echo $b;
    echo 111;
    exit;
}
public function test(){
    echo '成功';
}

很奇怪,在通过make方法获取实例化对象$services的时候,没有触发他的__construct()构造函数,没有输出$a,$b和111,但是$services->test()却成功执行了,输出了'成功'.
如果是这样,请问各位大神,如果我希望在controller中引入和执行services文件夹下的类来分担一部分业务逻辑的实现,我要怎么引入呢?我觉得App::make()这个方法是很好的,不需要手动require,直接获取到了实例化对象,可是为什么成功得到了实例化对象但是却没有执行构造函数输出111呢?我到底怎么才能在c层通过App::make()来传入参数给services层的构造函数呢?
期待大家的帮助,谢谢各位大神了.

滿天的星座
滿天的星座

reply all(3)
淡淡烟草味

I don’t know how you succeeded. At least I followed your approach and tested it locally, but it was unsuccessful (my Laravel is version 5.4).

I also looked at the relevant code. First of all, this method does not support passing parameters to the constructor. App::make('className')

If you need to pass parameters to the constructor, please use

. App::makeWith('className', [param1, param2, ...])

The code implementation uses reflection to check whether the constructor needs to pass parameters:

1. If no parameters are required, instantiate directly
2. If parameters need to be passed and the parameters are instantiable classes, try to instantiate This class (loop into the logic of
), and pass the instantiated class as a parameter to App::makeApp::makeWith()3. If parameters need to be passed, and the parameters are non-instantiable parameters (such as variables without type hints, the type hints are integers) , string, floating point, etc.), then further check whether there are default parameters. If there are default parameters, pass the default parameters to the constructor. If there are no default parameters, an exception will be thrown, as shown below:

黄舟

Forget about the static class directly. I later found out that it needs to be instantiated every time. Although automatic instantiation is injected into the controller, calling it in other places has to be done manually, so it is all static classed by me. . . . .

刘奇

Can’t dependency injection solve it?

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!