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

return [
    'providers' => [
        'services' => [
            'logger' => '\MaplePHP\Foundation\Log\StreamLogger',
            'lang' => '\MaplePHP\Foundation\Http\Lang',
            'responder' => '\MaplePHP\Foundation\Http\Responder',
            'cookies' => '\MaplePHP\Foundation\Http\Cookie',
            'YourServiceClass' => '\NamespaceTo\YourServiceClass'
        ]
    ]
];

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:

<?php
namespace Http\Controllers;

use MaplePHP\Http\Interfaces\ResponseInterface;
use MaplePHP\Http\Interfaces\RequestInterface;
use MaplePHP\Foundation\Http\Provider;
use Http\Controllers\BaseController;

class Pages extends BaseController
{
    public function __construct(Provider $provider)
    {
        $provider->YourServiceClass()->yourMethod();
    }
}

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:

public function __construct(Provider $provider)
{
    $provider->set("YourServiceClass", \NamespaceTo\YourServiceClass:class);
    $provider->YourServiceClass()->yourMethod();
}

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:

return [
    'providers' => [
        'services' => [
            'logger' => [
                "handlers" => [
                    '\MaplePHP\Foundation\Log\StreamLogger' => ["emergency", "alert", "critical"],
                ],
                "events" => [
                    '\MaplePHP\Foundation\Mail\PHPMailerTest'
                ]
            ],
            'lang' => '\MaplePHP\Foundation\Http\Lang',
            'responder' => '\MaplePHP\Foundation\Http\Responder',
            'cookies' => '\MaplePHP\Foundation\Http\Cookie',
            'YourServiceClass' => '\NamespaceTo\YourServiceClass'
        ]
    ]
];

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