Welcome to Abdul Malik Ikhsan's Blog

Zend Framework 2 : Forward – Redirect – Render

Posted in Teknologi, Tutorial PHP, Zend Framework 2 by samsonasik on June 8, 2012

Forward, Redirect, Render. Adalah 3 hal yang paling penting kita ketahui ketika membuat aplikasi berbasis web. Ketiga hal ini berhubungan erat dengan proses Http Response dalam hal mau  diapakan atau dibawa ke mana request yang diterima.

Forward terjadi ketika proses selanjutnya terjadi secara internal, alamat di address bar browser tidak berubah, dan jika dilakukan reload terhadap web browser, maka browser akan melakukan ulang request dari sebelumnya.
Redirect adalah 2 langkah proses, di mana aplikasi memerintahkan browser untuk keluar dari alamat pertama, dan menuju alamat berikutnya, alamat address berubah, dan browser tidak akan melakukan ulang request dari sebelumnya, karena sudah berada di alamat kedua, dan tidak ada hubungannya lagi dengan alamat pertama.
sedang Render adalah proses menampilkan view.
Contoh penggunaan Forward, Redirect,dan Render misalkan pada kasus kita akan menyapa pengunjung web dengan nama. Tetapi sebelum pengunjung disapa, pengunjung harus melakukan input nama terlebih dahulu, seperti berikut :


Pada gambar di atas, alamat di browser tertera /hello sedang /hello seharusnya berisi salam sapa kepada user, tapi karena user belum mengisi nama, maka halaman diforward ke halaman loginpage, yang secara alamat tidak terlihat di browser. Codingnya bisa dilihat di bawah ini :

    //hello page
    public function helloAction()
    {
        //do hello page, if not authenticated, forward login page 😉
        if ( ! $this->getSessContainer()->hellogreeting){
           return $this->forward()->dispatch('Test\Controller\Auth', array('action'=>'loginpage'));
        }

        $viewmodel = new ViewModel();
        $viewmodel->greeting = $this->getSessContainer()->hellogreeting;

        $viewmodel->setTemplate('test/auth/hello-success');
        //already have session hellogreeting ? so render the view !
        return $viewmodel;
    }

    //do login page ...
    public function loginpageAction()
    {
        if ( ! $this->getSessContainer()->hellogreeting){
            $request = $this->getRequest();
            if ($request->isPost()){
                $nama = $request->getPost('nama', false);
                if ($nama){

                    $this->getSessContainer()->hellogreeting = 'Hello '.$nama;
                    //session filled, redirect to hello page 😉
                    return $this->redirect()->toRoute('default',
                                              array('controller'=>'test-auth', 'action'=>'hello'));
                }
            }
        }
        return array();
    }

Pada saat selesai melakukan pengisian dan submit, maka akan diredirect menuju halaman /hello yang sesungguhnya, dan me-render hello-success.phtml. Setelah sukses, akan tampil seperti berikut :

Coding controller lengkapnya sebagai berikut :

namespace Test\Controller;

use Zend\Mvc\Controller\ActionController,
    Zend\View\Model\ViewModel,
    Zend\Session\Container as SessionContainer;

class AuthController extends ActionController
{
    protected $sesscontainer ;

    private function getSessContainer()
    {
        if (!$this->sesscontainer) {
            $this->sesscontainer = new SessionContainer('zftutorial');
        }
        return $this->sesscontainer;
    }

    //do login page ...
    public function loginpageAction()
    {
        if ( ! $this->getSessContainer()->hellogreeting){
            $request = $this->getRequest();
            if ($request->isPost()){
                $nama = $request->getPost('nama', false);
                if ($username){

                    $this->getSessContainer()->hellogreeting = 'Hello '.$nama;
                    //session filled, redirect to hello page 😉
                    return $this->redirect()->toRoute('default', 
                                   array('controller'=>'test-auth', 'action'=>'hello'));

                }
            }
        }
        return array();
    }

    public function logoutAction()
    {
        //unset session 😉
        $this->getSessContainer()->offsetUnset('hellogreeting');
        return $this->redirect()->toRoute('default',
                                   array('controller'=>'test-auth', 'action'=>'hello'));
    }

    //hello page
    public function helloAction()
    {
        //do hello page, if not authenticated, forward login page 😉
        if ( ! $this->getSessContainer()->hellogreeting){
           return $this->forward()->dispatch('Test\Controller\Auth', array('action'=>'loginpage'));
        }

        $viewmodel = new ViewModel();
        $viewmodel->greeting = $this->getSessContainer()->hellogreeting;

        $viewmodel->setTemplate('test/auth/hello-success');
        return $viewmodel;
    }
}

Done !

Referensi :
http://www.javapractices.com/topic/TopicAction.do?Id=181
http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html
http://stackoverflow.com/questions/1647594/zend-framework-what-this-forward-is-doing
http://stackoverflow.com/questions/8990195/how-to-use-zend-session-in-zf2

6 Responses

Subscribe to comments with RSS.

  1. dadan rosnawan said, on June 8, 2012 at 3:28 pm

    mksih ilmunya mas, saya lgi belajar zend juga…..

  2. samsonasik said, on June 8, 2012 at 3:34 pm

    iya, sama2 😉

  3. Max Gulturyan said, on May 14, 2013 at 2:21 pm

    how i can redirect from Module.php ?
    class Module extends T4\Module {

    public function onBootstrap(MvcEvent $event) {
    $em = $event->getApplication()->getEventManager();
    $em->attach(MvcEvent::EVENT_DISPATCH, array($this, ‘check’), 100);
    }

    public function check(MvcEvent $event) {
    $serviceManager = $event->getApplication()->getServiceManager();

    $auth = new AuthenticationService();

    if (!$auth->hasIdentity()) {
    // redirect to /login-form
    }

    }

    • samsonasik said, on May 15, 2013 at 9:11 am

      for checking authentication, you should using route event first instead of dispatch, like the following :

          public function onBootstrap(MvcEvent $e)
          {
              $eventManager        = $e->getApplication()->getEventManager();
              
              $eventManager->attach('route', array($this, 'check'));
              
              $moduleRouteListener = new ModuleRouteListener();
              $moduleRouteListener->attach($eventManager);
          }
          
          public function check(MvcEvent $e)
          {
              $application   = $e->getApplication();
              $sm            = $application->getServiceManager();
      		$sharedManager = $application->getEventManager()->getSharedManager();
              
              $sharedManager->attach('Zend\Mvc\Controller\AbstractActionController','dispatch', function($e) use ($sm) {
      			$controller = $e->getTarget();
                   $auth = new AuthenticationService();
                  if (!$auth->hasIdentity() && get_class($controller) != 'SanAuth\Controller\AuthController') {	
                          return $controller->redirect()->toRoute('login');
                  }
              },2);
          }
      
  4. seyferx said, on April 17, 2015 at 11:36 am

    Translate it in English please

    • samsonasik said, on April 18, 2015 at 2:38 pm

      this is very old post, you can use google translate 😛


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: