Phalcon initialize 和 onConstruct在Controller和Model中的初始化

Phalcon 中在Controller和Model中的初始化方法容易比较混淆的有initialize() 和 onConstruct();

值得注意的是initialize() 在控制器的一次request只会执行一次, 在Model中也是只会执行一次.
因此在控制器Controller1中执行initialize()后, 后面的代码再次使用new Controller1(), 或者再调用new Controller2()是不会执行Controller1或Controller2中的initialize方法的.

Model模型同理, 但和controller不同的是, ?不同的Model 会各自调用一次自己的initialize方法, 第二次再创建同一个Model时就不会再调用该model的initialize方法(phalcon 2.06版本). ?使用以下跟踪知道, __construct 会调用onConstruct()方法, 然后然后是initialize(), 最后又是onConstruct();

class ModelBase extends Model{

   public function initialize() {
        parent::__construct();
        echo get_class($this)."1111\n";
   }

   public function onConstruct() {
        echo get_class($this)."2222\n";     
   }
}

 

若要实现类似__construct()构造函数的效果, 可以使用onConstruct(). 在Phalcon/Mvc/Model 定义了__construct() 为final, 因此直接使用__construct()也不推荐.

public function onConstruct() {
    if(is_null($this->m_check_uid) OR $this->m_check_uid<=0)
        $this->m_check_uid = !empty(\CSQ::$mCheckId ) ? \CSQ::$mCheckId  : 1;
    $this->m_check_id=$this->getDI()->getShared('session')->get('uname');
}

查看cphalcon的Zephir源码也说明了这一点; 控制器中, 再次路由分发是不会再调用initialize;

	/**
	 * Dispatches a handle action taking into account the routing parameters
	 *
	 * @return object
	 */
	public function dispatch()
	{
            ..........
			/**
			 * Call the 'initialize' method just once per request
			 */
			if wasFresh === true {

				if method_exists(handler, "initialize") {
					handler->initialize();
				}

				/**
				 * Calling afterInitialize
				 */
				if eventsManager {
					if eventsManager->fire("dispatch:afterInitialize", this) === false {
						continue;
					}

					// Check if the user made a forward in the listener
					if this->_finished === false {
						continue;
					}
				}
			}
            ............
        }

模型model一次请求每个model只执行一次自身的

	/**
	 * Initializes a model in the model manager
	 */
	public function initialize( model) -> boolean
	{
		var className, eventsManager;

		let className = get_class_lower(model);

		/**
		 * Models are just initialized once per request
		 */
		if isset this->_initialized[className] {
			return false;
		}

onConstruct 在Controller和Model构造函数中每次新建都会执行一次

abstract class Controller extends Injectable implements ControllerInterface
{

	/**
	 * Phalcon\Mvc\Controller constructor
	 */
	public final function __construct()
	{
		if method_exists(this, "onConstruct") {
			this->{"onConstruct"}();
		}
	}
}

以及:

abstract class Model implements EntityInterface, ModelInterface, ResultInterface, InjectionAwareInterface, \Serializable { 
		/**
		 * This allows the developer to execute initialization stuff every time an instance is created
		 */
		if method_exists(this, "onConstruct") {
			this->{"onConstruct"}();
		}
	}

Leave a Reply

Your email address will not be published. Required fields are marked *