Laravel 4:对如何使用 App::make() 感到困惑
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21680795/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel 4: Confused about how to use App::make()
提问by Theo Kouzelis
I am trying to follow the repository pattern outlined in this article http://code.tutsplus.com/tutorials/the-repository-design-pattern--net-35804#highlighter_174798And I am trying to instantiate a class in Laravel using App::make() (Which I am guessing is Laravel's factory pattern?) and I am trying to parse arguments to my class but I can't work out how to do it.
我正在尝试遵循本文中概述的存储库模式http://code.tutsplus.com/tutorials/the-repository-design-pattern--net-35804#highlighter_174798我正在尝试使用 App 在 Laravel 中实例化一个类::make() (我猜这是 Laravel 的工厂模式?)我正在尝试解析我的类的参数,但我不知道该怎么做。
Code:
代码:
namespace My;
class NewClass {
function __construct($id, $title)
{
$this->id = $id;
$this->title = $title;
}
}
$classArgs = [
'id' => 1,
'title' => 'test',
]
$newClass = App::make('My\NewClass', $classArgs);
Can anyone point to an example of how to use App::make() or have I gone in the completely wrong direction and shouldn't be using App::make()?
谁能指出一个如何使用 App::make() 的例子,或者我是否走上了完全错误的方向,不应该使用 App::make()?
采纳答案by Theo Kouzelis
The good people in the Laravel forum answered this one for me http://laravel.io/forum/02-10-2014-laravel-4-confused-about-how-to-use-appmake
Laravel 论坛的好心人为我解答了这个http://laravel.io/forum/02-10-2014-laravel-4-confused-about-how-to-use-appmake
Pretty much if you can bind custom instantiation code with App::bind(); like so
如果您可以使用 App::bind(); 绑定自定义实例化代码,那就差不多了。像这样
App::bind('My\NewClass', function() use ($classArgs) {
return new My\NewClass($classArgs['id'], $classArgs['title']);
});
// get the binding
$newClass = App::make('My\NewClass');
回答by cheelahim
App is actually a facade for Laravel IoC container usually used for automatic resolution. Understanding of IoC concept is vital for complex application development but small projects will benefit from well architecture for sure. I would recommend to dive into Laravel documentationfirst and try some examples on Service Providers, Bindings and Automatic Resolution.
App 实际上是 Laravel IoC 容器的门面,通常用于自动解析。理解 IoC 概念对于复杂的应用程序开发至关重要,但小型项目肯定会受益于良好的架构。我建议先深入研究 Laravel文档,然后尝试一些有关服务提供者、绑定和自动解析的示例。
Speaking about your example:
说到你的例子:
namespace My;
class NewClass {
function __construct($id, $title)
{
$this->id = $id;
$this->title = $title;
}
}
$newClass = App::make('My\NewClass', [1, 'test']);