工厂方法中的逻辑是否可以接受?

时间:2016-11-18 14:42:34

标签: php drupal

我正在创建一个工厂方法,用于创建Drupal模块(对象)的集合。

在通过工厂方法创建此集合时,我希望确保我们只将模块添加到实现特定挂钩的集合中。 (在非Drupal术语中,这基本上意味着模块[对象]属于某种类型)。

所有这些过滤器逻辑都​​在工厂方法(包括依赖注入原则)中执行,以返回实现所需钩子的模块集合。

我想我的问题是......这是一种可接受的方法吗?在工厂方法等中包含这种逻辑级别是不错的做法。

有问题的方法:createFromModuleKeysImplementingHook

<?php

/**
 * Class ModuleCollectionFactory.
 *
 * Contains static factory methods that can be implemented to create
 * ModuleCollection objects.
 *
 * @package RuralStack\Common\Module
 */
final class ModuleCollectionFactory {

    /**
     * Create a ModuleCollection object from an array of Module keys.
     *
     * The following creation method will (for each passed Module key) create
     * a Module object which then added into the returned ModuleCollection
     * object.
     *
     * @param array $moduleKeys
     *     An array of Module keys to create the ModuleCollection object from.
     *
     * @return ModuleCollection The populate ModuleCollection object.
     */
    public static function createFromModuleKeys(array $moduleKeys){
        $moduleCollection = new ModuleCollection();
        foreach($moduleKeys as $moduleKey){
            $moduleCollection->add(Module::create($moduleKey));
        }
        return $moduleCollection;
    }


    /**
     * This is the method in question that implements the logic
     *
     * Is this good or bad practice?
     *
     * Is there a better way of doing this?
     *
     * @param array $moduleKeys
     * @param $hookName
     * @param HookInformationInterface $hookInformation
     *
     * @return ModuleCollection
     */
    public static function createFromModuleKeysImplementingHook(array $moduleKeys, $hookName, HookInformationInterface $hookInformation){

        /**
         * $moduleKeys = array('my_module', 'test_module', 'hook_module');
         *
         * $hookName = 'some_hook';
         *
         * $modulesInvokingHook = array('tm_dule, 'hook_module', 'my_module');
         *
         * array_intersect = array('hook_module', 'my_module');
         * ^^^Create the Module collection object from these
         */

        /**
         * Get all of the module keys that implement the hook (function) passed
         * to the factory method. Returns an array of module keys that matches
         * the format of the passed $moduleKeys argument.
         */
         $modulesInvokingHook = $hookInformation->getHookImplementations($hookName);

         $moduleCollection = new ModuleCollection();
         foreach(array_intersect($moduleKeys, $modulesInvokingHook) as $moduleKey){
            $moduleCollection->add(Module::create($moduleKey));
         }
         return $moduleCollection;
     }

}

0 个答案:

没有答案