美文网首页
Laravel学习笔记

Laravel学习笔记

作者: Captain_tu | 来源:发表于2017-08-10 14:33 被阅读16次
    1. 服务提供,依赖自动注入

       php artisan make:provider FoodProvider  #创建自己的服务提供商
       class FoodServiceProvider extends ServiceProvider
       .....
       public function register() {
           $food = new \App\Services\FoodService("rice");
           $this->app->bind("food", function($app){
               return $food;
           });
           $this->app->instance("App\Services\FoodService", $food);
       }
      
       //App\Services\FoodService
       class FoodService {
           private $food;
           public function __construct($food){
               $this->food = $food;
           }
      
           public function start() {
               dump("Today's food is ".$this->food);
           }
       }
      
       //在config\app.php中注册自己的provider
       'providers'  =>  {
           App\Providers\FoodServiceProvider::class,
       }
      
       //然后可以使用这个服务了
       //route\web.php
       $food = App::make("food");
       $food->start();
       //IndexController
       public function __construct(\App\Services\FoodService $food) {
           $this->food = $food;
       }
      
       public function index(Request $request) {
           $this->food->start();
           resolve("food")->start();
      
           \App::make("food")->start();
           app()->make("food")->start();
           resolve("food")->start();
       }
      
    2. 使用Facade简化名称

       //\App\Facades\FoodFacade.php
       namespace App\Facades;
       use Illuminate\Support\Facades\Facade;
      
       class FoodFacade extends Facade {
           public static function getFacadeAccessor() {
               return "food";
           }
       }
       //config\app.php
       'alias' => {
           'Food' => App\Facades\FoodFacade::class,
       }
      
       //IndexController@index
       \Food::start();

    相关文章

      网友评论

          本文标题:Laravel学习笔记

          本文链接:https://www.haomeiwen.com/subject/rrdhrxtx.html