bestit/commercetools-filter-bundle

商业工具的筛选和搜索实现

8.3.0 2018-03-26 13:39 UTC

README

为商业工具添加筛选和搜索实现。它仍然在内部使用commmercetools/php-sdk

安装

步骤 1:下载Bundle

打开命令行,进入您的项目目录,并执行以下命令以下载此bundle的最新稳定版本

$ composer require bestit/commercetools-filter-bundle

此命令需要您全局安装了Composer,如Composer文档中的安装章节中所述。

步骤 2:启用Bundle

然后,通过将其添加到项目中的app/AppKernel.php文件中注册的bundle列表中启用该bundle。

<?php
// app/AppKernel.php

// ...
class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
            // ...

            new BestIt\Commercetools\FilterBundle\BestItCommercetoolsFilterBundle(),
        );

        // ...
    }

    // ...
}

步骤 3:配置Bundle

最小配置(仅所有必需字段)

# Minimum configuration for "BestItCommercetoolsFilterBundle"
best_it_commercetools_filter:
    
    # Client service id of commerce tools sdk client
    client_id: app.commercetools.client
    
    # Sorting. At least one sorting options must exist
    sorting:
    
        # Default sorting to use if no sorting is selected
        default: name_asc
        
        # This is an array with all available sortings.
        choices:
            name_asc:
            
                # Translation key
                translation: sorting_name_asc
                
                # Api query for sdk
                query: 'name.de asc'

最大配置(所有必需和可选字段)

# Maximum configuration for "BestItCommercetoolsFilterBundle"
best_it_commercetools_filter:

    # Used translation domain (default "messages")
    translation_domain:   messages

    # Product normalizer (service id / implement interface)
    product_normalizer_id: best_it_commercetools_filter.normalizer.empty_product_normalizer

    # Client service id of commerce tools sdk client
    client_id:            ~ # Required

    # Optional facets factory config provider (service id / implement interface)
    config_provider_id:   best_it_commercetools_filter.provider.empty_facet_config_provider

    # Generator for filter urls
    url_generator_id:     best_it_commercetools_filter.generator.default_filter_url_generator

    # Cache life time. Enum Attribute labels are cached to minimize CommerceTools requests.
    # DEPRECATED: Do not use. Switch to enum_normalizer
    cache_life_time:      86400
    
    # Optional query for defining a base category. If used, only products under the base category will be selected. (default: null)
    base_category_query: 'custom(fields(alias="_SHOP_ROOT"))'
 
    # Sorting. At least one sorting options must exist
    sorting:              # Required

        # The default sort
        default:              ~ # Required
        
        # Default Sorting for the listing pages
        default_listing:      ~ # optional, if not set fallback to default sorting
        
        # Default Sorting for the search page
        default_search:       ~ # optional, if not set fallback to default sorting

        # Define the sorting id, the translation key and sort query. This is an array with all available sortings.
        choices:              # Required

            # Prototype
            key:

                # Api query for sdk (default: null for relevance sorting) 
                query:                ~

                # Translation key
                translation:          ~ # Required

    # Pagination settings
    pagination:

        # Products per page
        products_per_page:    20

        # Neighbours at pagination 1 => "1 2 3" | 2 => "1 2 3 4 5"
        neighbours:           1

    # View settings
    view:

        # Default view type (eg. grid, list)
        default:              list

    # Facet config
    facet:

        # Translation key for reset button or false for disable reset button
        reset:                reset

        # Translation key for reset button or false for disable submit button
        submit:               submit
    
    # Suggest config
    suggest:
        
        # Use fuzzy suggest (default: true)
        enable_fuzzy:         false
        
        # The fuzziness level is quantified in terms of the Damerau-Levenshtein distance.
        # If null, the platform selects level based on the length of the searched text 
        # Default: null
        fuzzy_level:          2
        
        # Mark matching variants with "isMatchingVariant". (default: false)
        match_variants:       true
        
    # Search config
    search:
        
        # Use fuzzy search (default: true)
        enable_fuzzy:         false
             
        # The fuzziness level is quantified in terms of the Damerau-Levenshtein distance.
        # If null, the platform selects level based on the length of the searched text
        # Default: null
        fuzzy_level:          2
                   
        # Mark matching variants with "isMatchingVariant". (default: false)
        match_variants:       true
        
    # Enum Normalizer
    # CommerceTools only returns enum keys. We have to normalize it.
    # This bundle ships one standard way - but you can define your own normalizer as well
    enum_normalizer:
    
        # Switch this normalizer on / off (default: true)
        enable: false
        
        # You can define your own cache pool (default: see id below)
        cache_id: cache.app
        
        # Time in seconds (default: 86400)
        cache_life_time: 60
        
    # Category Normalizer
    # CommerceTools only returns category id's. We have to normalize it.
    # This bundle ships one standard way - but you can define your own normalizer as well
    category_normalizer:
    
        # Switch this normalizer on / off (default: true)
        enable: false
        
        # You can define your own cache pool (default: see id below)
        cache_id: cache.app
        
        # Time in seconds (default: 86400)
        cache_life_time: 60      
          
        # Optional facet filter mode for listing (default: 'none')
        # Possible values:
        #   - none: No filter will be applied
        #   - parent: Only direct childrens categories will be shown
        #   - ancestors: All childrens and subchildrens will be shown
        facet_filter_type: 'parent'

用法

列表

只需在您的列表控制器中执行筛选管理器的listing方法。它需要Symfony请求对象和当前列表类别(Commercetools对象)以创建列表请求。

示例

// ListingController.php

    public function indexAction(Request $request, Category $category): array
    {
        $result = $this->get('best_it_commercetools_filter.manager.filter_manager')->listing($request, $category);
        
        return [
            'products' => $result->getProducts(),
            'totalProducts' => $result->getTotalProducts(),
            'context' => $result->getContext(),
            'pagination' => $result->getPagination(),
            'sorting' => $result->getSorting(),
            'facetForm' => $result->getForm()
        ];
    }

搜索

只需在您的列表控制器中执行筛选管理器的search方法。它需要Symfony请求对象和搜索字符串以创建搜索请求。

示例

// SearchController.php

    public function indexAction(Request $request, Category $category): array
    {
        $result = $this->get('best_it_commercetools_filter.manager.filter_manager')->search($request, $request->query->get('search'));
        
        return [
            'products' => $result->getProducts(),
            'totalProducts' => $result->getTotalProducts(),
            'context' => $result->getContext(),
            'pagination' => $result->getPagination(),
            'sorting' => $result->getSorting(),
            'facetForm' => $result->getForm()
        ];
    }

产品规范器

在大多数情况下,需要将产品规范化以供前端使用。您可以选择筛选bundle中的基础规范器之一,或者如果您实现了ProductNormalizerInterface并添加了服务ID到app配置,则可以使用您自己的规范器。筛选bundle包含两个基础规范器

  • ArrayProductNormalizer:将ProductProjection对象转换为数组。
  • EmptyProductNormalizer:仅返回未规范化的ProductProjection

EmptyProductNormalizer将在您未填写product_normalizer_id参数(@ config.yml)时使用。

术语规范器

在有些情况下,您必须规范化标签术语。Commercetools仅提供枚举键和类别ID等键,这对于您的前端来说不够。此bundle包含两个默认规范器

  • CategoryNormalizer:将类别ID转换为其实际名称
  • EnumAttributeNormalizer:将枚举键转换为其标签

但是,您也可以定义自己的TermNormalizer。只需实现TermNormalizerInterface并将标签best_it_commercetools_filter.term_normalizer添加到您的服务中。请记住在您的配置中禁用默认规范器。

如果您想跳过一个术语,只需抛出SkipTermException。不再应用其他规范器,并且该术语不会在前端显示。

配置提供者ID

您可以添加您自己的筛选配置提供者。只需实现FacetConfigProviderInterface并将您的服务ID添加到config_provider_id(@ config.yml)。如果没有填写config_provider_id参数(@ config.yml),则将使用筛选bundle的默认提供者,它返回没有筛选。

URL生成器

过滤器包需要创建URL,但路由名称可能在不同的项目中有所不同。因此,您可以通过url_generator_id参数添加自己的URL生成器来创建正确的URL。生成器需要实现FilterUrlGeneratorInterface接口。如果您不填写字段,则包将使用其自己的默认生成器。

事件

请求事件

您可以使用过滤器和建议后事件修改commercetools客户端请求。检查所有事件,请参阅SuggestEventFilterEvent类。

示例用法:扩展请求

// FilterRequestSubscriber.php

class FilterRequestSubscriber implements EventSubscriberInterface
{
    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents()
    {
        return [
            SuggestEvent::PRODUCTS_REQUEST_POST => 'onProductsFilterRequest',
            FilterEvent::PRODUCTS_REQUEST_POST => 'onProductsSuggestRequest'
        ];
    }

    /**
     * On products request for filter
     * @param ProductProjectionSearchRequestEvent $event
     */
    public function onProductsFilterRequest(ProductProjectionSearchRequestEvent $event)
    {
        $request = $event->getRequest();

        $request
            ->expand('masterVariant.attributes[*].value')
            ->expand('productType');

        $event->setRequest($request);
    }

    /**
     * On products request for suggest
     * @param ProductProjectionSearchRequestEvent $event
     */
    public function onProductsSuggestRequest(ProductProjectionSearchRequestEvent $event)
    {
        $request = $event->getRequest();

        $request
            ->expand('categories[*]')
            ->expand('masterVariant.attributes[*].value[*].value')
            ->expand('productType');

        $event->setRequest($request);
    }
}