duandu8202 2019-06-05 07:28 采纳率: 0%
浏览 88
已采纳

PHPMD和对象类之间的耦合(CBO)

I'm working on a Magento 2 CRUD functionality following the best practices (best described here). On the project I'm working on we are using PHPMD (php mess detector). Among other rules, we have the CBO limit set to 13 (which I understand is the default). My repository is implementing the get, save, getList, delete, deleteById methods and the limit is already 12.

What would be best practice if I need to add other methods to this repository without overlapping the PHPMD CBO limit?

P.S. I think this can be the case for implementations in other frameworks/platforms as well, not strictly related to Magento 2.

  • 写回答

1条回答 默认 最新

  • dongyiba8082 2019-06-05 19:39
    关注

    This is one of the greatest rules that helps to keep your classes focused and easier to maintain. How many times have you seen that:

    class XXXRepository
    {
        public function findOneByCode($code);
        public function findOneByParams($params);
        public function findAllByParams($params);
        public function findActive($params);
        public function findForProductList($params);
        ... 5000 lines of spaghetti
    }
    

    Instead go for this, embrace interfaces, make your application depend upon abstractions, not implementation details:

    interface ProductByCode
    {
        public function findByCode(string $code): ?Product;
    }
    
    interface ProductsByName
    {
        public function findByName(string $name): array;
    }
    

    Using the Dependency Injection component you can alias an interface to its implementation. Go for implementation per each interface. You can make use of a abstract class which will help you communicate with the persistence layer via the framework of your choice.

    final class ProductByCodeRepository extends BaseRepository implements ProductByCode
    {
        public function findByCode(string $code): ?Product
        {
            return $this->findOneBy(['code' => $code]);
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用