47 lines
1.2 KiB
PHP
47 lines
1.2 KiB
PHP
|
|
<?php
|
|||
|
|
|
|||
|
|
namespace app\mzl\common\traits;
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 调用服务类的便捷工具
|
|||
|
|
*/
|
|||
|
|
trait ServiceCallTrait
|
|||
|
|
{
|
|||
|
|
/**
|
|||
|
|
* 实例缓存
|
|||
|
|
*/
|
|||
|
|
protected array $serviceCache = [];
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 调用指定 Service
|
|||
|
|
*
|
|||
|
|
* @param string $serviceClass 服务类名(必须继承 BaseService)
|
|||
|
|
* @return object
|
|||
|
|
*/
|
|||
|
|
protected function callService(string $serviceClass): object
|
|||
|
|
{
|
|||
|
|
if (!isset($this->serviceCache[$serviceClass])) {
|
|||
|
|
$this->serviceCache[$serviceClass] = new $serviceClass();
|
|||
|
|
}
|
|||
|
|
return $this->serviceCache[$serviceClass];
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 快捷调用某服务下某个方法
|
|||
|
|
*
|
|||
|
|
* @param string $serviceClass
|
|||
|
|
* @param string $method
|
|||
|
|
* @param array $args
|
|||
|
|
* @return mixed
|
|||
|
|
*/
|
|||
|
|
protected function callServiceMethod(string $serviceClass, string $method, array $args = []): mixed
|
|||
|
|
{
|
|||
|
|
$service = $this->callService($serviceClass);
|
|||
|
|
|
|||
|
|
if (!method_exists($service, $method)) {
|
|||
|
|
throw new \BadMethodCallException("Method {$method} does not exist in {$serviceClass}");
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
return call_user_func_array([$service, $method], $args);
|
|||
|
|
}
|
|||
|
|
}
|