2

私は Silex プロジェクトに参加しており、さまざまな処理にクラスを使用しています。

$connection = new Connection($app);
$app->match('/connection', function () use ($app, $connection) {
    $connexion->connectMember();
    return $app->redirect($app['url_generator']->generate('goHome'));
})->method('GET|POST')->bind('doConnection');

クラス「接続」の関数「connectMember()」には、次のものがあります。

   [...]
if($isMember){
   [...]
}else{
   return $this->_app['twig']->render(
      'message.twig', 
      array('msg' => "This member does not exist.", 'class' => 'Warning'));
}
   [...]

しかし、 render () メソッドが機能していません。表示したいエラーメッセージが表示されず、代わりに「$ app-> redirect (...)」が起動されます。

クラスが現在のオブジェクト Silex\Application を使用するようにするにはどうすればよいですか? カスタム クラスを Silex アプリケーションのインスタンスにバインドするためのより良い方法はありますか?

ご回答ありがとうございます。


版 : 情報追加

私が使用する場合:

return $connexion->connectMember();

エラーメッセージが表示されます。しかし、それは良い解決策ではありません。「接続」クラスは、このコードも使用する他のクラスを呼び出します。

$this->_app['twig']->render(...). 

$ this->_app (私のクラスに存在) をコントローラーで作成された変数 $app に対応させる方法は?

4

2 に答える 2

6

Connection(またはConnexion??) クラスのサービスを作成し、アプリケーションを注入します。

use Silex\Application;

class Connection
{
    private $_app;

    public function __construct(Application $app)
    {
        $this->_app = $app;
    }

    // ...
}
$app['connection'] = function () use ($app) {
    return new Connection($app); // inject the app on initialization
};

$app->match('/connection', function () use ($app) {
    // $app['connection'] executes the closure which creates a Connection instance (which is returned)
    return $app['connection']->connectMember();

    // seems useless now?
    return $app->redirect($app['url_generator']->generate('goHome'));
})->method('GET|POST')->bind('doConnection');

詳細については、silexpimpleのドキュメントを参照してください(pimple は silex が使用するコンテナーです)。

于 2013-10-24T17:41:47.953 に答える
1

依存性注入に $app->share(...) を使用している場合は、次のようにセットアップできます (これは疑似コードです)。

<?php
namespace Foo;
use Silex\Application as ApplicationBase;

interface NeedAppInterface {
   public function setApp(Application $app);
}

class Application extends ApplicationBase {
  // from \Pimple
  public static function share($callable)
  {
    if (!is_object($callable) || !method_exists($callable, '__invoke')) {
      throw new InvalidArgumentException('Service definition is not a Closure or invokable object.');
    }

    return function ($c) use ($callable) {
      static $object;

      if (null === $object) {
        $object = $callable($c);
        if ($object instanceof NeedAppInterface) {
          // runtime $app injection
          $object->setApp($c); // setApp() comes from your NeedAppInterface
        }
      }
      return $object;
    };
  }
}

今これをやっている:

$app['mycontroller'] = $app->share(function() use ($app) {
   return new ControllerImplementingNeedAppInterface();
});

$app['mycontroller'] を呼び出すと、自動的に $app が設定されます!

PS : ->share() を使用したくない場合は、\Pimple::offsetGet() が呼び出すため、__invoke($app) を使用してみてください:p

于 2014-02-25T18:59:00.640 に答える