Symfony 3.xでは、Doctrine EntitiesをJSON-Responses(JMSSerializerおよびFOSRestBundle)として提供するAPIレイヤーを使用しています。SymfonyのカスタムObjectNormalizersシリアライゼーションコンポーネント。コンテナ対応の抽象基底クラスでクラス継承を使用する
これらのAPIクラスのカップルは、コンテナを認識する必要があります。現在、グローバルな$kernel
を使用しています。
これは私がこれまでのところ(非常に簡略化)しようとしたものです:
抽象クラス
abstract class ApiWrapper implements ContainerAwareInterface
{
use ContainerAwareTrait;
protected $container;
public function setContainer(ContainerInterface $container = null)
{
$this->container = $container
}
}
BaseClassの
protected class BaseApi extends ApiWrapper
{
//...some stuff
}
RealApiClass1
protected class MyApi1 extends BaseApi
{
protected $entity;
public function __construct(SomeEntityClass $entity) {
$this->entity = $entity;
}
}
RealApiClass2
protected class MyApi2 extends BaseApi
{
protected $entity;
public function __construct(AnotherEntityClass $entity) {
$this->entity = $entity;
}
}
services.yml
services:
bundle.api_wrapper:
class: ApiWrapper
abstract: true
shared: false // to make sure to get a new instance everytime it's called
calls:
- [ setContainer, [ @service_container ] ]
bundle.base_api:
class: BaseApi
parent: api_wrapper
bundle.my_api:
class: MyApi
parent: base_api
コントローラ
$myApi = new MyApi1($myEntity);
$myApi
にはプロパティコンテナがありますが、それはnull
です。 このシナリオでコンテナを共有する方法はありますか?あなたは一例として、コンテナ経由でAPIを取得する必要がありますコントローラで
私はあなたが達成しようとしていることを知りませんが、コンテナの初期設計を破るのではなく、なぜそれをして適切な解決策を見つけるのかを正しく説明したいと思うかもしれません。ここのすべては中期的にも非常に悪いものです。サイクリック依存関係の問題が発生していますか? –
既に指摘したように、新しい演算子はSymfonyコンテナに関する知識がありません。 1つの可能性は、APIの工場クラスを作ることです。しかし実際には、完全な容器を注入する理由はほとんどありません。 – Cerad
@Ceradに感謝、あなたは工場のクラスのためのいくつかの方向を教えてくれますか?定義されたサービスのカップル(実際には現時点では2)を注入できるかどうかは問題ありません。 – LBA