要するに私の質問: 複数のコントローラーに単一のファクトリーを使用できますか?
詳細:
/config/autoload/global.phpには、次のようなグローバルな非モジュール固有の設定がいくつかあります。
return array(
'settings' => array(
'setting_a' => 'foo',
'setting_b' => 'bar'
),
// More ZF default configuration ...
);
ここで、常に呼び出すことなく、すべてのコントローラーでこれらの設定にアクセスできるようにしたいと考えて$this->getServiceLocator()->get('config')
います。
したがって、私の考えは、構成配列に注入されるクラス属性$settings
を myに導入することでした。AbstractController
のコンストラクターで構成を直接取得しようとしましたAbstractController
。ただしgetServiceLocator()
、その時点では準備ができていないようで、NULL を返します。
すべてのコントローラーのコントローラー ファクトリを構築し、次のように設定を挿入できます。
class ControllerFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $serviceLocator) {
$config = $serviceLocator->get('config');
return new \MyModule\Controller\MyController($config['settings']);
}
}
しかし、それは何度も何度も同じでしょう。私の質問は、複数のコントローラーに単一のファクトリーを使用できますか?
私のmodule.config.phpでは、複数のコントローラに対して 1 つのファクトリ クラスを指定できます。
return array(
'controllers' => array(
'factories' => array(
'MyModule\Controller\MyControllerA' => 'MyModule\Factory\ControllerFactory',
'MyModule\Controller\MyControllerB' => 'MyModule\Factory\ControllerFactory',
'MyModule\Controller\MyControllerC' => 'MyModule\Factory\ControllerFactory',
)
),
);
しかし、ファクトリでは、実際の Controller オブジェクトを手動で返す必要があります (上記の例を参照)。もちろん、これは Controller ごとに 1 つの Factory でのみ機能します。
希望、私は私の問題を明確にしました。
更新 2013 年 3 月 24 日:
私は最初にイニシャライザを作成することで提案された解決策に従いましたが、構成の注入のためだけにそれを使用することは決して好きではありませんでした。
それで、私は掘り下げ続け、設定を受け取るためのコントローラープラグインを作成することになりました。
プラグインのコードは次のようになります。
use Zend\Mvc\Controller\Plugin\AbstractPlugin;
class Settings extends AbstractPlugin
{
protected $settings;
public function __invoke()
{
$config = $this->getController()->getServiceLocator()->get('Config');
if (isset($config['settings']) && is_array($config['settings'])) {
$this->settings = $config['settings'];
}
return $this->settings;
}
}
module.config.phpにプラグインを追加した後
'controller_plugins' => array(
'invokables' => array(
'settings' => 'My\Controller\Plugin\Settings',
)
),
を呼び出すだけで、コントローラー内の設定に簡単にアクセスできます$this->settings()
。これが誰にも役立つことを願っています。