How to get Symfony session variable in model?

前端 未结 2 1573
忘掉有多难
忘掉有多难 2021-01-07 11:07

How can I pass session variable in symfony model without using sfContext::getInstance()?

相关标签:
2条回答
  • 2021-01-07 11:18

    The recommended way is called dependency injection, and works like this: you create a setUser() method in your model file, that saves the given parameter to a private property:

    class Foo {
      private $_user;
    
      public function setUser(myUser $user) {
        $this->_user = $user;
      }
    
      // ... later:
    
      public function save(Doctrine_Connection $conn = null) {
        // use $this->_user to whatever you need
      }
    }
    

    This looks clumsy, because it is. But without you answering the question what are you trying to do? I cannot give an alternative.

    Recommended articles:

    • What is Dependency Injection? - a post series on Fabien Potencier's blog
    • Dependency Injection - the design patter in detail on wikipedia
    0 讨论(0)
  • 2021-01-07 11:20

    Session variables should be stored as user's attributes.

    // in an action: 
    $this->getUser()->setAttribute('current_order_id', $order_id);
    

    See how to get it back.

    // later on, in another action, you can get it as:
    $order_id = $this->getUser()->getAttribute('current_order_id', false);
    if($order_id!==false)
    {
        // save to DB
    } else {
        $this->getUser()->setFlash('error', 'Please selected an order before you can do stuff.');
        // redirect and warn the user to selected an order
        $this->redirect('orders');
    }
    
    0 讨论(0)
提交回复
热议问题