2017-02-16 4 views
-2

バンドルの下のライブラリフォルダにあるsymfonyプロジェクトでライブラリを作成しました。私もサービスに追加したライブラリからリポジトリを取得できません

namespace AppBundle\Library; 

use Symfony\Component\DependencyInjection\ContainerInterface as Container; 
use Doctrine\Common\Persistence\ObjectManager; 

class MooLibrary 
{ 
    private $container = null; 
    private $em   = null; 

    public function __construct(ObjectManager $em, Container $container) 
    { 
     $this->container = $container; 
     $this->em   = $em; 
    } 

    public function getTypeContent($type = null, $id = 0) 
    { 
     $content = array(); 
     $dataClass = ucfirst($type); 

     $content = $this->em->getRepository('AppBundle:Post')->findOneById($id); 

     return $content; 
    } 
} 

post_type: 
     class: AppBundle\Library\MooLibrary 
     arguments: [ @doctrine.orm.entity_manager, @service_container ] 

これは私にエラーを与える:ここでのコードはどのように見えるかだ

Using $this when not in object context

+3

通常、エラーメッセージは、$ thisを静的メソッドの内部で使用しようとしていることを示しています。投稿されたコードには表示されません。あなたは何かMooLibrary :: getContentType()のような何かをしていますか? – Cerad

+0

これは非常に有用なコメントです。はい、このクラスはライブラリですので、 'PostController'というコントローラ内で' MooLibrary :: getContentType'を使用します。 – shaNnex

+1

Laravel Facadeの背景から来ていると思いますか? Symfonyは違う。バック・ダウンして依存性注入を理解しなければならない。 @ Stonyの答えは$ this-> get( 'moolib')で良いヒントを与えます。 – Cerad

答えて

2

私はあなたの完全なYMLを知りませんあなたのファイルはserviceセクションに定義されています。

services: 
    moolib: 
     class: AppBundle\Library\MooLibrary 
     arguments: [ @doctrine.orm.entity_manager, @service_container ] 

クラスが正しいように見えます。

その後、あなたがそれを呼び出すことができます。

$this->get('moolib'); 

もう一つは、symfonyアプリケーションをビルドする必要がありますどのように一部の仕様があるということです。そのため通常は

https://symfony.com/doc/current/bundles/best_practices.html

あなたはベストプラクティスですが、それはオプションだフォルダDependencyInjectionを作ります。

関連する問題