Laravel 4: Confused about how to use App::make()

匿名 (未验证) 提交于 2019-12-03 02:59:02

问题:

I am trying to follow the repository pattern outlined in this article http://code.tutsplus.com/tutorials/the-repository-design-pattern--net-35804#highlighter_174798 And 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.

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()?

回答1:

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 documentation first and try some examples on Service Providers, Bindings and Automatic Resolution.

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']); 


回答2:

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

Pretty much if you can bind custom instantiation code with App::bind(); like so

App::bind('My\NewClass', function() use ($classArgs) {     return new My\NewClass($classArgs['id'], $classArgs['title']); });  // get the binding $newClass = App::make('My\NewClass'); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!