Tìm hiểu service provider trong laravel

Auto JX2 VNG onlineaz.vn

Chương trình hỗ trợ chơi Game JX2 onlineaz.vn : nhiều chức năng , an toàn

Chi tiết xem tại : http://autojx2vng.onlineaz.vn

*

SuperToolonlineaz.vn

SuperToolonlineaz.vn – Tiện ích đa năng ClickMouse , Taskkill trên window onlineaz.vn 2020

Chi tiết xem tại : Here

*

TQC Dzogame Window onlineaz.vn

Phần mềm hỗ trợ chơi Tam Quốc Chí DzoGame onlineaz.vn Tool 2020

Chi tiết xem tại : Here

×Close Everything you need for your next creative project. Over 4.5 million digital products created by a global community of designers, developers, photographers, illustrators & producers.

Try to click… Try to resize

More…See more options
Tiện ích Header. Tra cứuHỗ trợ tra cứu trực tuyến Tra cứu menu Tra cứu thông dụng Tra cứu những thông tin cần thiết Tra cứu thông dụng Menu Giá vàng – các thứ Tra cứu những thông tin cần thiết Giá vàng – các thứ Menu Từ điển – Bản đồ Tra cứu những thông tin cần thiết Từ điển – Bản đồ Menu Websmater toolsOpen on hover to the left& fix on click Websmater tools Menu Websmater toolsHỗ trợ cho thiết kế website& Websmater tools Menu Net toolsCông cụ cho Internet& Net tools Menu Facebook toolsCông cụ cho Facebook& Facebook tools Menu Convert toolsCông cụ chuyển đổi văn bản& Video Audio Convert tools Menu
Tài khoản
Account

Sign in

Email
Password
Sign in

Đăng ký tài khoản? Sign UP Free

Quên mật khẩu

Lost Your Password?

Create new account

Email
Password
Confirm password
I have read and agree to ourTerms of use and Privacy Policy.
Create an account

Forgotten your Username?

Enter your email address, you signed up with (or entered in your settings), and we”ll send you an email with your username.

Bạn đang xem:

Send it to me!

If you”ve forgotten your username and password, you must first retrieve your username (using your email address) and then reset your password using those details.

Forgot your password?

Enter your username, and we”ll send you an email with a link and instructions to reset your password. If you signed up without an email address (or removed it from settings), visit the FAQ.

Send it to me!

If you”ve forgotten your username and password, you must first retrieve your username (using your email address) and then reset your password using those details.

Subscribe to our mailing list

Get the freebies from us and latest updates about YourApp! We hate spam as much as you do, trust us we won”t give your details away to other people.

Your email address
Your Name
Subscribe

Contact us

Submit
$5
×
Danh mục : Thủ thuật Laravel

Tìm hiểu Service Provider trong Laravel

Tìm hiểu Service Provider trong Laravel

Tìm hiểu Service Provider trong Laravel

PHPLaravel

Xin chào anh em , gặp lại anh em trong bài viết chia sẻ lần này trong seriesLaravel và những điều thú vịmình muốn chia sẻ những điều mình đã tìm hiểu được vềService Providertrong Laravel. Như các bạn biết đấy, bài viết lần trước mình đã chia sẻ vềService Container. Thì bài viết này mình muốn chia sẻ vềService Providertrong Laravel – trung tâm của việc khởi tạo tất cả các ứng dụng trong Laravel. Chúng mình cùng đi tìm hiểu nó nhé.

1. Service Provider là gì ?

Như mình cũng nói ở trên rồi,Service Providernó là trung tâm của việc khởi tạo tất cả các ứng dụng trong Laravel, các thành phầncoresẽ được khởi tạo từService Provider.

Chúng ta để ý đến file app/config/app.php các bạn sẽ thấy ngay đoạn khai báo này

/*

|————————————————————————–

| Autoloaded Service Providers

|————————————————————————–

|

| The service providers listed here will be automatically loaded on the

| request to your application. Feel free to add your own services to

| this array to grant expanded functionality to your applications.

|

*/

‘providers’ =>

/*

* Laravel Framework Service Providers…

*/

IlluminateAuthAuthServiceProvider::class,

IlluminateBroadcastingBroadcastServiceProvider::class,

IlluminateBusBusServiceProvider::class,

IlluminateCacheCacheServiceProvider::class,

IlluminateFoundationProvidersConsoleSupportServiceProvider::class,

IlluminateCookieCookieServiceProvider::class,

IlluminateDatabaseDatabaseServiceProvider::class,

IlluminateEncryptionEncryptionServiceProvider::class,

IlluminateFilesystemFilesystemServiceProvider::class,

IlluminateFoundationProvidersFoundationServiceProvider::class,

IlluminateHashingHashServiceProvider::class,

IlluminateMailMailServiceProvider::class,

IlluminateNotificationsNotificationServiceProvider::class,

IlluminatePaginationPaginationServiceProvider::class,

IlluminatePipelinePipelineServiceProvider::class,

IlluminateQueueQueueServiceProvider::class,

IlluminateRedisRedisServiceProvider::class,

IlluminateAuthPasswordsPasswordResetServiceProvider::class,

IlluminateSessionSessionServiceProvider::class,

IlluminateTranslationTranslationServiceProvider::class,

IlluminateValidationValidationServiceProvider::class,

IlluminateViewViewServiceProvider::class,

/*

* Package Service Providers…

*/

/*

* Application Service Providers…

*/

AppProvidersAppServiceProvider::class,

AppProvidersAuthServiceProvider::class,

AppProvidersBroadcastServiceProvider::class,

AppProvidersEventServiceProvider::class,

AppProvidersRouteServiceProvider::class,

>,

Các bạn có thấy quen không, mỗi lần chúng ta mà cài đặt package nào qua composer thì chúng ta cũng phải khải báoService Providertrong mảngprovidersnày. Tất cả những service provider này sẽ được load vào trong ứng dụng, những đôi khi chỉ một số mới được load khi service được yêu cầu.Nói chúng định nghĩaService Providertrongdocumentationnó còn mơ hồ quá. Chuyển sang tí cách dùng để giải thích nhá. Các bạn có thấyAppProvidersAppServiceProvider::classđược khai báo trong mảngproviderstrong file app/config/app.php không ? Nó chính là mộtService Providerđó. Thay vì luôn luôn phải sử dụngapp()->bind() app()->instance() app()->singleton(), thì bây giờ việc bindings trong file app/config/app.php thì sẽ được truyền vào dưới dạng tên class để Laravel có thể tự động tìm tới Service Provider tương ứng và bind chúng vào Container. Các Service Provider là nơi sẽ thực hiện việc khai báo service và bind vào trong Service Container.

Chú ý

Các bạn có thể tìm vào thư mục app/boostrap/app.php thì các bạn sẽ thấy đoạn code sau đây:

$app->singleton(

IlluminateContractsHttpKernel::class,

AppHttpKernel::class

);

$app->singleton(

IlluminateContractsConsoleKernel::class,

AppConsoleKernel::class

);

$app->singleton(

IlluminateContractsDebugExceptionHandler::class,

AppExceptionsHandler::class

);

Chỉ có duy nhất file này mới thực hiện binding trực tiếp các service , còn đâu ngoài ra bạn sẽ không tim thấy còn chỗ nào bind trực tiếp như này nữa đâu. Tất cả đều được đăng ký tên class để thực hiện việc binding trong mảngproviderstrong file config/app.php.

Xem thêm:

2. Class abstract ServiceProvider

Chúng ta thử cùng tìm hiểu một ServiceProvider nhé.

namespace IlluminateRedis;

use IlluminateSupportArr;

use IlluminateSupportServiceProvider;

class RedisServiceProvider extends ServiceProvider

{

/**

* Indicates if loading of the provider is deferred.

*

*
var bool

*/

protected $defer = true;

/**

* Register the service provider.

*

*
return void

*/

public function register()

{

$this->app->singleton(‘redis’, function ($app) {

$config = $app->make(‘config’)->get(‘database.redis’);

return new RedisManager(Arr::pull($config, ‘client’, ‘predis’), $config);

});

$this->app->bind(‘redis.connection’, function ($app) {

return $app->connection();

});

}

/**

* Get the services provided by the provider.

*

*
return array

*/

public function provides()

{

return ;

}

}

Nào chúng ta cùng đi phân tích vềRedisServiceProviderchút nhé Các bạn có thấyRedisServiceProviderextends từ abstract classServiceProvider. Ta tìm thấy abstract classServiceProviderthì thấy có hàmregister()nên tất cả việc binding đều phải viết trong hàm này. Tiếp theo ta thấy biến$defer = true;trong class . Biến này có ý nghĩa rằng nếu ta gán cho nó giá trị bằngtruethì quá trình binding sẽ không được thực hiện khi service không được gọi. Ví dụ như là khi bạn dùng câu lệnhApp::make(‘redis’)thì quá trình binding mới được thực hiện , một instance RedisManager mới được tạo ra. Và từ lần gọi sau thì instance RedisManager có trong Service Container rồi nên cứ gọi ra mà dùng thôi. Tại sao chúng ta nên khai báo$defer = true??? Đó chính là để tăng hiệu năng cho ứng dụng của bạn, chỉ gọi khi cần thiết chứ không load bừa phứa lên rồi để đấy không sử dụng . Điều này khiến hiệu năng ứng dụng của bạn kém hơn. Cuối cùng là hàmprovider()- hàm này sẽ cho Laravel biết là provider của bạn sẽ trả về service gì.

3. Thuộc tính bindings và singletons

Ở các phiên bản Laravel 5.3 trở về trước không có 2 thuộc tính này, nhưng ở phiên bản Laravel 5.6 thì xuất hiện thêm 2 thuộc tính này. Nếu như chúng ta muốn binding nhiều nhiều thì thay vì chúng ta viết cácapp()->bind() app()->singleton()thì chúng ta có thể khai báo như sau:

namespace AppProviders;

use AppContractsServerProvider;

use AppContractsDowntimeNotifier;

use IlluminateSupportServiceProvider;

use AppServicesPingdomDowntimeNotifier;

use AppServicesDigitalOceanServerProvider;

class AppServiceProvider extends ServiceProvider

{

/**

* All of the container bindings that should be registered.

*

*
var array

*/

public $bindings =

ServerProvider::class => DigitalOceanServerProvider::class,

>;

/**

* All of the container singletons that should be registered.

*

*
var array

*/

public $singletons =

DowntimeNotifier::class => PingdomDowntimeNotifier::class,

>;

}

Khi Service Provider được load bởi Laravel thì Laravel sẽ tự động check những thuộc tính$bindings $singletonsnày để tự động binding. Đây là một điểm thuận tiện cho phiên bản Laravel 5.6.

4. Phương thưc boot()

Nếu như bạn muốn đăng ký mộtview composerthì bạn sẽ viết trong hàmboot()

namespace AppProviders;

use IlluminateSupportServiceProvider;

class ComposerServiceProvider extends ServiceProvider

{

/**

* Bootstrap any application services.

*

*
return void

*/

public function boot()

{

view()->composer(‘view’, function () {

//

});

}

}

Hàm này sẽ được gọi khi tất cả các Service Provider được đăng ký xong.

Xem thêm:

5. Kết luận

Vậy qua trên mình cũng chia sẻ những gì mình đã tìm hiểu được vềService Providertrong Laravel. Mong rằng bài viết của mình cũng một phần nào làm sáng tỏ một chút vềService Provider. Cảm ơn các bạn đã đọc bài chia sẻ của mình.

6. Tham khảo

https://laravel.com/docs/5.6/providers https://viblo.asia/p/laravel-beauty-tim-hieu-ve-service-provider-zb7vDVJnMjKd

Chuyên mục: