-
服务提供,依赖自动注入
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(); }
-
使用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();
网友评论