We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Best method implement logic event Model

Hi all

I have a question ?. I assuming have two model implement method beforeDelete and beforeUpdate

    class Job extends ModelBase
    {
    [...]
    **
     * Implements hook beforeDelete
     *
     * Check permission before deleted task
     *
     * @return  bool
     */
    public function beforeDelete()
    {
       // d($this->idUser);
        if ($this->idUser != (int)$this->getDI()->getSession()->get('auth')['id']) {
            $this->getDI()->getflashSession()->error(t('The object is not owner, it can\'t be deleted'));

            return false;
        }

        return true;
    }
    /**
     * Implements hook beforeUpdate
     *
     * Check permission before updated task
     *
     * @return  bool
     */
    public function beforeUpdate()
    {
        if ($this->idUser != (int)$this->getDI()->getSession()->get('auth')['id']) {
            $this->getDI()->getflashSession()->error(t('The object is not owner, it can\'t be edit'));
            return false;
        }
        return true;
    }

Then model Task

    class Task extends ModelBase
    {
    [...]
    **
     * Implements hook beforeDelete
     *
     * Check permission before deleted task
     *
     * @return  bool
     */
    public function beforeDelete()
    {
       // d($this->idUser);
        if ($this->idUser != (int)$this->getDI()->getSession()->get('auth')['id']) {
            $this->getDI()->getflashSession()->error(t('The object is not owner, it can\'t be deleted'));

            return false;
        }

        return true;
    }
    /**
     * Implements hook beforeUpdate
     *
     * Check permission before updated task
     *
     * @return  bool
     */
    public function beforeUpdate()
    {
        if ($this->idUser != (int)$this->getDI()->getSession()->get('auth')['id']) {
            $this->getDI()->getflashSession()->error(t('The object is not owner, it can\'t be edit'));
            return false;
        }
        return true;
    }

In this case two model, but many model used code above . How to reusable code ?

Thanks all



7.9k
Accepted
answer

You can use PHP feature Trait : https://php.net/manual/en/language.oop5.traits.php

here is some example:

CommonBehaviour

<?php

namespace Jowy\Phrest\Models;

trait CommonBehaviour
{
    public function beforeCreate()
    {
        $this->created_at = date("Y-m-d H:i:s");
    }

    public function beforeUpdate()
    {
        $this->updated_at = date("Y-m-d H:i:s");
    }
}

and use them on desired model, it should do the job.



58.4k

@Prasetyo

This is perfect Thanks



8.0k
edited Nov '14

@Thiện U can use Phalcon Behaviors. Example see in incubator. It more powerful than traits.



58.4k

@web777, I will review it :)

edited Jan '15

Hi all. Can I catch beforeFind using model behavior?