1
votes

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
Interface per method, implementation per interface. This is called SRP from the SOLID. This is a great rule. Prevents people from creating monstrous god classes.emix
can you please elaborate on this (maybe add an answer to the question if you need more room for the explanation). I would be really interested in an example if I'm not asking too much!Radu

1 Answers

0
votes

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]);
    }
}