Skip to content

Instantly share code, notes, and snippets.

@MayMeow
Created May 9, 2018 20:44
Show Gist options
  • Save MayMeow/b737b3ff287b0eb87827eb773f4cc19e to your computer and use it in GitHub Desktop.
Save MayMeow/b737b3ff287b0eb87827eb773f4cc19e to your computer and use it in GitHub Desktop.
CakePHP Services
<?php
namespace MayMeow\Cake\Bl\Service;
use Cake\Core\ObjectRegistry;
trait ServiceAvareTrait
{
protected $serviceLocator;
protected $defaultServiceLocator = ServiceLocator::class;
public function loadService($service, array $constructorArgs = [], $assignProperty = true)
{
$serviceInstance = $this->getServiceLocator()->load($service, $constructorArgs);
if (!$assignProperty) {
return $serviceInstance;
}
list(, $name) = pluginSplit($service);
if (isset($this->{$name})) {
trigger_error(__CLASS__ . "::$%s is already in use.", E_USER_WARNING);
}
$this->{$name} = $serviceInstance;
return $serviceInstance;
}
public function getServiceLocator()
{
if (null == $this->serviceLocator) {
$class = $this->defaultServiceLocator;
$this->serviceLocator = new $class();
}
return $this->serviceLocator;
}
public function setServiceLocator(ObjectRegistry $locator)
{
$this->serviceLocator = $locator;
}
}
<?php
namespace MayMeow\Cake\Bl\Service;
use Cake\Core\ObjectRegistry;
use Cake\Core\App;
use Cake\Core\Exception\Exception;
class ServiceLocator extends ObjectRegistry
{
/**
* @param string $class
* @return bool|null|string
*/
protected function _resolveClassName($class)
{
return App::className($class, 'Service', 'Service') ? : null;
}
/**
* @param string $class
* @param string $plugin
*/
protected function _throwMissingClassError($class, $plugin)
{
if (!empty($plugin)) {
$message = sprintf(
"Service `%s` in plugin `%s` not found.",
$class,
$plugin
);
} else {
$message = sprintf(
"Service class `%s` not found.",
$class
);
}
throw new Exception($message);
}
/**
* @param string $class
* @param string $alias
* @param array $config
* @return mixed
*/
protected function _create($class, $alias, $config)
{
if (empty($config)) return new $class();
return new $class(...$config);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment