2

I keep reading about the use of [interface]::getList within Magento 2 and how it's the preferred method for fetching records. For example:

namespace Magento\Customer\Api;

interface CustomerRepositoryInterface
{
    /**
     * Retrieve customers which match a specified criteria.
     *
     * This call returns an array of objects, but detailed information about each object’s attributes might not be
     * included. See https://devdocs.magento.com/codelinks/attributes.html#CustomerRepositoryInterface to determine
     * which call to use to get detailed information about all attributes for an object.
     *
     * @param \Magento\Framework\Api\SearchCriteriaInterface $searchCriteria
     * @return \Magento\Customer\Api\Data\CustomerSearchResultsInterface
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    public function getList(\Magento\Framework\Api\SearchCriteriaInterface $searchCriteria);
}

Can anyone explain the how to use it and why it's the preferred method?

1
  • Is it not the preferred method? Anyone? May 15, 2019 at 14:00

1 Answer 1

9
  • Magento2 tries to keep everything as loosely coupled as possible. This includes separation between data retrieval and any data keeping|searching logic. In Magento 1 you would use collections everywhere you needed data (for e.g.) you would add filters and orders on the collection. Removing the collection class was practically impossible (without refactoring all the usages) . By adding a layer of abstraction (The repository layer) and using a contract for retrieving data (search Criteria) the code becomes more flexible. Anyone who needs data gives you a search criteria and expects a search result, they don't need to know the behind the scene logic on how the data is retrieved. Now let's say at a given point you want to change the logic on how you retrieve your data, as long the contract is not broken the application will work.
  • You can implement your own getlist method using a collection processor (Magento\Framework\Api\SearchCriteria\CollectionProcessor) and a searchResultFactory (Magento\Framework\Api\Search\SearchResultInterfaceFactory), the code will look something like this:

         /**
         * Load Subscription data collection by given search criteria
         *
         * @param \Magento\Framework\Api\SearchCriteriaInterface $criteria
         * @return SearchResultInterface
         */
        public function getList(\Magento\Framework\Api\SearchCriteriaInterface $criteria)
        {
            $searchResult = $this->searchResultsFactory->create();
            $collection = $this->collectionFactory->create();
            $this->collectionProcessor->process($criteria, $collection);
            $searchResult->setItems($collection->getItems());
            $searchResult->setTotalCount($collection->getSize());
    
            return $searchResult;
        }
    

    To call the method you would need a searchCriteria builder. (Magento\Framework\Api\SearchCriteriaBuilder) and maybe the (Magento\Framework\Api\SortOrderBuilder)

    The code will look something like this

    $this->sortOrderBuilder->setField(self::END_DATE);
    $this->sortOrderBuilder->setDescendingDirection();
    $this->searchCriteriaBuilder->addSortOrder($this->sortOrderBuilder->create());
    
    $this->sortOrderBuilder->setField(self::ID);
    $this->sortOrderBuilder->setDescendingDirection();
    $this->searchCriteriaBuilder->addSortOrder($this->sortOrderBuilder->create());
    
    $this->searchCriteriaBuilder
        ->addFilter(self::CUSTOMER_ID, $subscription->getCustomerId())
        ->addFilter(self::PRODUCT_ID, $subscription->getProductId())
        ->addFilter(self::ID, $subscription->getId(), 'neq')
        ->setPageSize(1);
    
    /** @var SearchResultInterface $searchResult */
    $searchResult = $this->subscriptionRepository->getList($this->searchCriteriaBuilder->create());
    

I suggest you experiment on your own with this. You can take a look at how other getList() methods are implemented in the core. Alan Storm has a useful article on it. Vinai Kopp has a useful post about repositories as well. The docs also guide you through searching with repositories here

2
  • Thanks for that. I did see the vinai kopp article before but he covered a lot in that single article and it blew my mind a little. I missed the Alan storm article. That was good to read. Alan Storm IMHO is easier to follow. It's interesting that he made a note about not sure whether his implementation was correct. Either way you've summarised it quite nicely. Out of curiosity what is your approach? Do you use repository interfaces or stick with more m1 style factories? Or use a bit of everything based on the task? May 26, 2019 at 17:57
  • 1
    @DominicXigen I did very little work on M1, and I hated it, I still do. Coming from a heavy OOP background I find using repositories as the normal way to do things. The trouble is that this approach is really verbose and development takes more time. I personally use repositories almost every time, exceptions make a real tight deadline for a proof of concept or when Magento forces me to use other methods for data persistence|retrival. On the other hand I understand why some people would prefer not to use them. May 26, 2019 at 18:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.