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