How to Get a Service? In Codeigniter 4

In CodeIgniter 4, you can access or retrieve a Service in various ways, depending on your application’s structure and coding preferences. Below are the methods you can use to get a service:

1. Using the service() Helper Function

  • This is the simplest and most concise way to access a service.
  • The service() function retrieves a shared instance of the specified service.

Example:

$logger = service('logger'); // Get the logger service
$logger->info('This is an info log.');

$validation = service('validation'); // Get the validation service
$validation->setRules(['name' => 'required']);

2. Using the \Config\Services Class

  • The \Config\Services class provides static methods for accessing services.
  • By default, it returns shared instances unless explicitly specified otherwise.

Example:

$logger = \Config\Services::logger(); // Get the logger service
$logger->info('This is an info log.');

$email = \Config\Services::email(); // Get the email service
$email->setTo('example@example.com');
$email->setSubject('Test Email');
$email->setMessage('This is a test email.');
$email->send();

3. Getting Non-Shared Instances

  • If you need a fresh instance of a service (not shared across the application), pass false as an argument to the service method in the \Config\Services class.

Example:

$logger1 = \Config\Services::logger();       // Shared instance
$logger2 = \Config\Services::logger(false); // New instance

// logger1 and logger2 are different objects

4. Custom Services

  • If you’ve created custom services in the Services class, you can retrieve them in the same way.
  • Example of defining and using a custom service:
// In App\Config\Services.php
namespace App\Config;

use CodeIgniter\Config\BaseService;

class Services extends BaseService
{
    public static function customService($getShared = true)
    {
        if ($getShared) {
            return static::getSharedInstance('customService');
        }

        return new \App\Libraries\CustomService();
    }
}

// Usage
$customService = \Config\Services::customService();

5. Dependency Injection

  • You can inject a service into a class by defining it as a dependency in the constructor or method.
  • CodeIgniter’s Controller and Model base classes do not support auto-injection directly, but you can manually pass services during instantiation.

Example:

class MyController extends BaseController
{
    protected $logger;

    public function __construct()
    {
        $this->logger = \Config\Services::logger();
    }

    public function index()
    {
        $this->logger->info('Logging from index method.');
    }
}

6. Using Service Injection in Testing

  • When writing tests, you can inject mock services to replace actual ones.
  • CodeIgniter provides the injectMock method for this purpose.

Example:

$mockLogger = $this->createMock(\CodeIgniter\Log\Logger::class);
\Config\Services::injectMock('logger', $mockLogger);

$logger = \Config\Services::logger(); // Returns the mocked instance

7. Accessing Built-In Services

CodeIgniter provides several pre-defined services. Here are a few commonly used ones:

  • Logger: \Config\Services::logger();
  • Validation: \Config\Services::validation();
  • Email: \Config\Services::email();
  • Database: \Config\Services::database();
  • Session: \Config\Services::session();

Example:

$session = \Config\Services::session(); // Access session service
$session->set('key', 'value');

Summary Table of Access Methods

MethodShared InstanceNew InstanceUsage Example
service(‘name’)YesNo$logger = service(‘logger’);
\Config\Services::method()YesYes (with false)$logger = \Config\Services::logger();
Custom-defined servicesYesYes (with false)$custom = \Config\Services::customService();

Share the Post:

Related Posts