Files
usedcar/app/mzl/common/traits/ServiceCallTrait.php
T
2025-05-14 13:19:23 +08:00

47 lines
1.2 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?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);
}
}