Welcome to Abdul Malik Ikhsan's Blog

Zend Framework 2 : EventManager

Posted in Tutorial PHP, Zend Framework 2 by samsonasik on April 30, 2012

Zend Framework 2 menghadirkan sebuah komponen yang sangat membantu dalam proses-proses seperti logging, debugging, serta caching. Komponen ini memungkinkan proses dieksekusi terjadi ketika sebuah fungsi dipanggil secara fleksibel. Tak hanya itu, parameter dari fungsi bisa didapatkan dari object Event yang dilewatkan.

Berikut contohnya :

require_once 'Zend/Loader/AutoloaderFactory.php';
Zend\Loader\AutoloaderFactory::factory();

use Zend\EventManager\EventManager,
    Zend\EventManager\Event;

class Identity
{
    public $events;

    public function  events()
    {
        if (!$this->events) {
            $this->events = new EventManager(__CLASS__);
        }

        return $this->events;
    }

    public function insert($nama, $alamat)
    {
        $params = compact("nama", "alamat");

        //insert into table Identity ..
        //............

        //give event afer insert 😉
        $this->events()->trigger(__FUNCTION__, $this, $params);
     }
}

$identity = new Identity();
$identity->events()->attach('insert', function (Event $e) {
    $fp = fopen("insert.log", 'a+');
    fwrite($fp, "insert data ".$e->getParam('nama')." berhasil pada tanggal : ".date('d-m-Y H:i:s')." \n");
});

$identity->insert('abdul malik ikhsan', 'jalan jakarta');

Referensi :
1. http://mwop.net/slides/2011-10-18-Zf2-Overview/
2. http://akrabat.com/zend-framework-2/an-introduction-to-zendeventmanager/
3. http://packages.zendframework.com/docs/latest/manual/en/zend.event-manager.html

4 Responses

Subscribe to comments with RSS.

  1. oky said, on November 14, 2012 at 5:46 am

    Kalau masalah error begini gimana ya?
    Warning: require_once(Zend/Loader.php) [function.require-once]: failed to open stream:

    • samsonasik said, on November 14, 2012 at 7:57 am

      berarti file Zend/Loader.php Ga ada. kemungkinan mas pakai zf1, tulisan saya kali ini buat zf2

  2. philtyphil said, on July 24, 2014 at 11:58 pm

    Mas, kalo even action pgn sebelum di insert gimana ?


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: