Service Provider
Service Provider, Container and Dependency Injector
MaplePHP/Container is primarily designed for efficiently passing class instances and anonymous functions to controllers and services. Utilize the Container to inject a class into the dependency injector, which in turn loads the class and its nested services seamlessly, resolving dependencies and preventing duplicate instances. Access the container either through the library or the service provider. In my example, I'll demonstrate using the service provider, which acts similarly to the Container but provides shortcuts for faster code writing. I might talk about the Container and Provider here and there, but just remember they are the same.
The Provider (Service Provider) already comes with some pre-initialized functionallity:
url: Used to build uri links and get URI path to directories
dir: Used to get paths to directories
date: Used to get current date
string: Used to modify strings
env: Used to get enviorment data
encode: Used to encode strings (protect against XSS)
lang: Get and set current language
local: Access the local language translations from current language
DB: Communication with the database
logger: Log data in log files
cookies: Create cookies
responder: Used to communicate with the frontend code.
Every service mentioned above will have its respective guide under the "Service Provider" section, which you can read later on.
Add service to the Service Provider
You can also add your own functionality, or rather add your own service to the provider, in a couple of ways.
Alternative 1:
The simplest way is to add your service to the provider config file /config/providers.php
YourServiceClass
has now been added to the provider and can be used without having to initiated it again.
To access YourServiceClass
you just need to access the Provider
like this:
You don't need to worry about initializing the Provider because the Dependency Injector will handle that for you.
Alternative 2
You can directly add your Service literally using the Provider:
If a service has already been set in the Provider, attempting to set it again will result in an error, indicating the need to avoid duplicates.
Event handler
The Event handler links an Event Class to a Service, ensuring that when the Service or specific methods within it are triggered, the associated Event class also activates. For instance, it can automatically send a notification email if the logger records an emergency text in the log file. See the example below:
That concludes our discussion on the Provider. Don't worry if you don't fully comprehend everything. In a couple of steps, I will start showing you some working examples that you can follow, but do not jump there now because the guide is designed for linear reading!
Let's proceed to the next step.
Last updated