<分区>
我有一组扩展通用类的服务,该类在它们之间提供一些通用功能。
一组特定的这些服务有一个共同点:它们使用 API 中的特定资源,因此它们有很多共同的代码(连接到 API 并执行一些 GET 或 POST,应用 API要求,基本上改变端点和要传递的参数数量)。
我的问题是,将这段代码抽象为特征是否不好?并在需要使用该特定代码段的任何服务上重用它?
举个例子:
trait ApiResource {
public function retrieve()
{
try {
// apply logic of the resource
} catch (\Exception $e) {
return false;
}
}
}
class Departments extends Generic {
use ApiResource;
public function createCache(Cache $cache)
{
$cache->storeDepartments($this->retrieve('departments', 200));
}
}
class Brands Generic {
use ApiResource;
public function createCache(Cache $cache)
{
$cache->storeBrands($this->retrieve('brands'));
}
}