Git Product home page Git Product logo

php-service-locator's Introduction

php-service-locator

release Packagist Version PHP Version Require license

build codecov

Компонент-контейнер для работы с экземплярами классов-служб. Реализует логику контейнера служб по шаблону проектирования "Локатор служб".

Структура

src/
--- exceptions/
------ ContainerObjectInvalidTypeException.php
--- interfaces/
------ ServiceInterface.php
--- ServiceLocator.php

В директории interfaces хранятся необходимые интерфейсы, которые необходимо имплементировать в при реализации собственных классов служб. Класс ServiceLocator выступает в качестве контейнера служб. В директории exceptions хранятся необходимые исключения. Исключение QueryStringNotFoundException исключение необходимо для обозначения ошибки типа служб в контейнере.

Примерная реализация функционала:

<?php

declare(strict_types = 1);

use mepihindeveloper\components\container\interfaces\ServiceInterface;
use mepihindeveloper\components\container\ServiceLocator;

error_reporting(E_ALL);
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');

require_once 'vendor/autoload.php';

$serviceLocator = new ServiceLocator();
// Анонимный класс используется в тестах, но можно реализовать собственный класс.
$logger = new class implements ServiceInterface {
    protected string $filePath;

    public function __construct(string $filePath = '') {
        $this->filePath = $filePath;
    }

    /**
     * Получает путь к файлу
     * 
     * @return string
     */
    public function getFilePath(): string {
        return $this->filePath;
    }
};
$serviceLocator->addInstance(get_class($logger), $logger);
var_dump($serviceLocator->has(get_class($logger)), $serviceLocator->get(get_class($logger)));

// OR

$serviceLocator->addService(get_class($logger), ['/var/www/']);
$logger = $this->serviceLocator->get(get_class($logger));
var_dump($logger->getFilePath()); // /var/www/

Доступные методы

ServiceLocator

Метод Аргументы Возвращаемые данные Исключения Описание
get(string $id) Идентификатор службы (класс объекта object::class) ServiceInterface ContainerObjectInvalidTypeException|NotFoundExceptionInterface Получает службу из контейнера
has(string $id): bool Идентификатор службы (класс объекта object::class) bool Проверяет наличие службы в контейнере
addService(string $id, array $params): void string $id Идентификатор класса-службы (object::class); array $params Аргументы конструктора класса-службы Добавляет класс-службу
addInstance(string $id, ServiceInterface $service): void string $id Идентификатор класса-службы (object::class); ServiceInterface $service Экземпляр класса-службы Добавляет экземпляр класс-службу

Контакты

Вы можете связаться со мной в социальной сети ВКонтакте: ВКонтакте: Максим Епихин

Если удобно писать на почту, то можете воспользоваться этим адресом: [email protected]

Мой канал на YouTube, который посвящен разработке веб и игровых проектов: YouTube: Максим Епихин

Поддержать меня можно переводом на Яндекс.Деньги: Денежный перевод

php-service-locator's People

Contributors

mepihindeveloper avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.