Zend Framework

Zend Framework - Doctrine ORM strange Zend Tool behavior.

Zend Framework - Doctrine ORM strange Zend Tool behavior.

Zend Framework... awesome.
Doctrine ORB... awesome.

Both of these combined.... PURE AWESOME.

I set up a project just at it says to on this page http://github.com/fmntf/zf-doctrine. It took some doing, but I got it working and was quite happy with my initial results. Then I needed to start a new project, so I just copied all the files, tweaked the DB name was flying with a new project... with one caveat.

One of the modules I created using a YAML file was not getting created in the DB when I ran zf build-project doctrine --reload. It was frustrating, I tried changing a bunch of things.

In the end the whole problem was that the module folder didn't have a controllers folder and that was it. So I created a controllers folder and then it created the corresponding tables in the db. I think this code has much to do with it

application/Bootstrap.php

<?php
 
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
  /**
   *  This will register all the module directories with ZF
   */
  public function _initModuleLoaders()
  {
      $this->bootstrap('Frontcontroller');
 
      $fc = $this->getResource('Frontcontroller');
      $modules = $fc->getControllerDirectory();
 
      foreach ($modules AS $module => $dir) {
          $moduleName = strtolower($module);
          $moduleName = str_replace(array('-', '.'), ' ', $moduleName);
          $moduleName = ucwords($moduleName);
          $moduleName = str_replace(' ', '', $moduleName);
 
          $loader = new Zend_Application_Module_Autoloader(array(
              'namespace' => $moduleName,
              'basePath' => realpath($dir . "/../"),
          ));
      }
  }
 
}

More Zend Framework Fun

More Zend Framework Fun

Zend Framework Form Hash Ajax

This one sucked hunting down the answer.

The problem. I would include a token (hash) in the form I was producing. I set the form as a checkbox that as soon as it's checked it fires off an AJAX request with the token, and data. The first time it worked great, every other time it would tell me the Token was missing. Hmmmm....

http://codeutopia.net/blog/2008/10/16/how-to-csrf-protect-all-your-forms...

Hi Jani, I got a work around for the problem. The real problem is this, for AJAX requests, it works for first time and not for the subsequent requests. The AJAX request was having the same token for all it’s requests but the plugin was generating unique token for all the requests. So is the mismatch / problem. That was the problem.
Workaround:
What I did was, for each AJAX request, I stopped generating a new token and used the already generated one to compare. So by this way I can cover for multiple AJAX requests. It could be vulnerable for the time that it lives and after that I will eject (logout) the user from the system and then they (attacker) will have to login again and get a token and then attack (if they wanted to really). That was it.

I never did find an answer yet, I did post it to StackOverFlow
http://stackoverflow.com/questions/2474774/how-to-use-zend-framework-for...

Instead I did the whole thing manually..

Form

class Form_GroupListForm extends Zend_Form
{
    public function  __construct($options = null)
    {
        parent::__construct($options);
 
        $this->setName('grouplist');
 
        $groupmodel = new Default_Model_Group();
 
        $groups = new Zend_Form_Element_MultiCheckbox('groups');
        $groups->addMultiOptions($groupmodel->getGroupList())
               ->setLabel('Groups')
               ->setDescription('Groups this person belongs to:')
               ->setAttrib('class', 'ajaxcheckbox')
                ;
 
        $token = new Zend_Form_Element_Hash('grouplisttoken');
        $token->setSalt('hello')
              ->setTimeout(3600)    // Form times out after one hour
              ->removeDecorator('HtmlTag')
              ->removeDecorator('Label');
 
 
        $myNamespace = new Zend_Session_Namespace('authtoken');
        $myNamespace->authtoken = $hash = md5(time());
        $auth = new Zend_Form_Element_Hidden('authtoken');
        $auth->setValue($hash)
             ->setRequired('true')
              ->removeDecorator('HtmlTag')
              ->removeDecorator('Label');
 
 
 
        $this->addElements(array($groups, $auth));
 
 
    }
}

Notice the session being generated then stored as a hidden field. Dumb that I have to basically replicate the hash feature, but the hash has an hop of 1, meaning that it can only be used for one page refresh then it expires. There should be a way to persist this token over several ajax calls.

Zend Framework Pagination

Zend Framework Pagination

This is a way to have Zend Framework Pagination (Paginator) working so that it remembers the query across mulitiple pages. This seemed like such a simple and obvious task, but the solution is not so obvious. The trick is to test if 'isPost()' then save the query to the session variable. That way when a visitor travels to page two we have the query in the session variable. No URL tricks or other tom foolery.

/IndexController.php

    public function searchAction()
    {
        $value = $this->_request->getPost('query');
 
        // Start a session
        $session = new Zend_Session_Namespace('value');
 
        // If $value is a post then the search has just been submitted.
        if ($this->getRequest()->isPost()) {
            $session->value = $value;
        }
 
        // Get the select from Zend_DB
        $amazon = new Model_Example();
        $result = $amazon->searchExample($session->value);
 
        // Assign Paginator data to view
        $this->view->paginator = $this->_addPaginator($result);
        $this->view->query = $session->value;
        $this->_helper->viewRenderer('list');
    }
 
    private function _addPaginator($select)
    {
        $page = $this->_getParam('page', 1);
        $paginator = new Zend_Paginator(new Zend_Paginator_Adapter_DbSelect($select));
        $paginator->setItemCountPerPage(self::ItemCountPerPage)
                  ->setCurrentPageNumber($page)
                  ->setPageRange(5);
        return $paginator;
    }

/layout/scripts/layout.phtml

<div id="search"><form action="/index/search" method="POST"><input type="text" name="query" id="query" value="<?php echo $this->query; ?>"><input type="submit" name="Submit" value="Submit"></form></div>

/views/scripts/index/list.phtml

<?php if($this->paginator): ?>
<div><?php echo $this->paginationControl($this->paginator, 'Sliding', 'pagination.phtml'); ?></div>
 
<?php foreach($this->paginator as $item): ?>
<!-- list your item data -->
<?php endforeach; ?>
 
<div><?php echo $this->paginationControl($this->paginator, 'Sliding', 'pagination.phtml'); ?></div>
<?php endif; ?>

Credit:
http://www.zfforums.com/zend-framework-components-13/databases-20/proble...

Setup PHPunit for testing Zend Framework application

Setup PHPunit for testing Zend Framework application

This was how I set up PHPUnit with my Zend Framework application. I'm very new to testing and have never set it up before.

<

ol>

  • Need to get PHPunit installed on the Apple Mac
    Try typing this in the command line (btw I prefer iTerm over the built in terminal).
    whereis phpunit
  • I tried a few different ways to install php, I'm not sure which one eventually installed it, but.... yeah I know sounds dumb, but when you try a bunch of different ways and then it 'just starts working' you lose track which way actually fixed it. Besides it was two weeks ago, I can't remember that far back. I do know that one of the has Xdebug turned on to generate the nice reports of code coverage.

    For example.

    Shane:tests shane$ whereis phpunit
    /usr/bin/phpunit
    Shane:tests shane$ phpunit --version
    PHPUnit 3.4.6 by Sebastian Bergmann.
     
    Shane:tests shane$ 

  • Now setup your environment. This is the hard part, since everyone does it different. The trouble is figuring out which pieces need to go where and why.
  • Bonus
    This will create a neat little tree of your folder structure

    ls -R | grep ":$" | sed -e 's/:$//' -e 's/[^-][^\/]*\//--/g' -e 's/^/   /' -e 's/-/|/' 

    So I have this structure for my application

       |-application
       |---configs
       |---controllers
       |---models
       |-----DbTable
       |---views
       |-----helpers
       |-----scripts
       |-------error
       |-------index
       |-library
       |-public
       |-tests
       |---application
       |-----controllers
       |-----models
       |---library
       |---log
       |-----report

    Notice the "test" folder with subfolders? Good.

    We now have the necessary folder, here are files

    tests/phpunit.xml

    <phpunit bootstrap="./bootstrap.php" color="true">
        <testsuite name="My Test Suite">
            <directory>./</directory>
        </testsuite>
     
        <filter>

    More Zend Framework Fun

    More Zend Framework Fun

    Sending email via Gmail

      $config = array(
          'ssl' => 'tls',
          'port' => 587,
          'auth' => 'login',
          'username' => 'youemail@gmail.com',
          'password' => 'yourpassword'
      );
     
      $gmail = new Zend_Mail_Transport_Smtp('smtp.gmail.com', $config);
      $mail = new Zend_Mail();
      $mail->addTo($this->to);
      $mail->setSubject($this->subject);
      $mail->setFrom($this->from);
      $mail->setBodyText($this->body);
     
      $mail->send($gmail);

    As you can see, you need to create an object for Gmail, then create an email object, then tell the email object to use the gmail ob

    Zend Framework Application Progress

    Zend Framework Application Progress

    Today I learned from Zend Framework.

    Redirecting visitors to their intended URI after login

    LoginForm.php

      ...
      // Grabs the requested URI from the server and stores it in a hidden field
      $this->addElement('hidden', 'referrer', array('value' => $_SERVER['REQUEST_URI']));
      ...

    Then after you complete authentication, send them to the referring URI

      if($form->getValue('referrer'))
          $this->_redirect($form->getValue('referrer'));
      $this->_redirect('index/index');

    Credits:
    http://stackoverflow.com/questions/1249274/redirect-to-previous-pa

    Zend Framework Application Progress

    Zend Framework Application Progress

    Tonight's programming lessons included

    • Removing Decorators (dt, dd HTML tags) from Zend_Form_Element_Hidden types. There are several Decorators by using removeDecorator
          $addressid = new Zend_Form_Element_Hidden('addressid');
          $addressid->setAttrib('id', 'form-addressid')
                    ->removeDecorator('HtmlTag')
                    ->removeDecorator('Label');
       

    Zend Framework Resources

    Zend Framework Resources

    I'll try to bring some of the recent lessons learned in Zend Framework here on the blog. The deeper I dig, I realize the framework is very well put together and powerful.

    • The official Zend Framework Manual True to PHP, Zend has a great manual with many examples, though, if you are looking for every explicit directions where to place code you may be disappointed. Since Zend is a very loosely coupled framework, they don't always assume you're using it in the Zend Application setting.
    Syndicate content