Tag Archive: zend framework


I spend quiet a lot of time on this one, I posted arround here and there to find the anwser on how to make a JsonRestStore happend with Zend Framework. There are quiet a few tutorials out there but my main problem was a response from the server when POST request was made (when creating a new document).

Well here’s the solution :
$this->getResponse()
->setHttpResponseCode(201)
->setHeader('Content-Type', 'application/json', true)
->setHeader("Location", 'http://mywebsite' . $this->_request->getRequestUri() . $id);

$params['id'] = $id;
return $params;

First : you need to send back a code 201. Second, you need to send the url of the store with the new id (ex : mysite/store/4
Then you need to send back the content of the item created + the id in order to be able to play with it with DOJO. Otherwise, no fun.

Here’s the dojo part of the code :

testStore = new dojox.data.JsonRestStore({jsId:"tStore", target:"/test/", idAttribute:"id" });

// Get the content of a form with a magic dojo query
data = {};
dojo.query(" textarea, .ArticleNewFormElement > input").forEach(function(node, index, arr){
if(node.id){
data[node.id] = dijit.byId(node.id).attr("value");
}
});

// Add the item to the DataStore
var newClient = clientsStore.newItem(data);

// Save it back to the server
clientsStore.save({onComplete:function(item) {

// Now you can play with the ID of the element you just created, so cool !
console.log(newClient.id);

}
});

Note that I changed a few variables here and there for my blog without rechecking the entire stuff so re-read it if you need to use it, but it works. JsonRestStore is your friend I tell you !

Advertisements

It’s sunday and I’m playing with Zend_Test. Here are some basic things that took me time to find out :
Grep simple text in the page :

  1. $this->assertQueryContentContains(‘body’, “your email is invalid”);

Verify unvalid users can not log in :

  1. $this->request->setMethod(‘POST’)
  2. ->setPost(array(
  3. ’email’ => ‘fakeaddress@fakedomain.com’,
  4. ‘password’ => ‘fakepassw’
  5. ));
  6. $this->dispatch(‘/user/login’);
  7. $this->assertNotRedirect();
  8. $this->assertFalse(Zend_Auth::getInstance()->hasIdentity());

The interesting part is the last part :

  1. $this->assertFalse(Zend_Auth::getInstance()->hasIdentity());

And, let’s test a form :

  1. $this->assertQueryCountMin(‘form’, 1);
  2. $this->assertQueryCountMin(‘input[name~=”email”]’, 1);
  3. $this->assertQueryCountMin(‘input[name~=”password”]’, 1);
  4. $this->assertQueryCountMin(‘input[name~=”submit”]’, 1);

Nothing fancy here, only some tips that can only make your discovering of Zend_Test easyer ! Happy testing !

This morning I wanted to play with the Zend_Dojo Editor in order to allow users to submit content. Honestly from what I saw I don’t really like the looks of it (checkout the microsoft version of a web editor in Sharepoint if you want to compare), but well I thought it’ll do the trick for the moment. So I added this in my form :

  1. $this->addElement(‘editor’, ‘content’,
  2. array(
  3. ‘editActionInterval’ => 2,
  4. ‘focusOnLoad’        => true,
  5. ‘height’             => ‘250px’,
  6. ‘inheritWidth’       => true,
  7. ));

And all I got was an error ! Why, because the Dojo editor exists only in the svn trunk for the moment (it seems to be scheduled for the 1.7 version). The question is : should that really stop you from using it ? Ok, you know the answer, so let’s go on to the second problem : how to get the framework from svn ? Unfortunately I couldn’t get an explanation from zend.com since the corresponding pages were down, so I had to google arround to find what I was looking for. And guess what, a simple command line does the trick :

  1. svn checkout http://framework.zend.com/svn/framework

And here you go…

Here are some tests functions I wrote for testing the validity of the access control lists of my website. Nothing fancy but it’s an exemple that may be usefull for begginners.

  1. private function CanAccess($url)
  2. {
  3. $this->dispatch($url);
  4. $this->assertNotResponseCode(‘404’);
  5. list($controller, $action) = explode(“/”, ereg_replace(“^/”, “”, $url));
  6. $this->assertController($controller);
  7. $this->assertAction($action);
  8. }
  9. private function CanNotAccess($url)
  10. {
  11. $this->dispatch($url);
  12. // if the user is Guest
  13. if(!Zend_Auth::getInstance()->hasIdentity())
  14. {
  15. $this->assertController(‘user’);
  16. $this->assertAction(‘login’);
  17. // CustomAclManager Should show a Login form
  18. $this->assertQueryCountMin(‘form’, 1);
  19. $this->assertQueryCountMin(‘input[name~=”email”]’, 1);
  20. $this->assertQueryCountMin(‘input[name~=”password”]’, 1);
  21. $this->assertQueryCountMin(‘input[name~=”submit”]’, 1);
  22. }
  23. // If user is logged In he’ll only get redirected
  24. else
  25. $this->assertRedirect;
  26. }
  27. private function LoginRealUser()
  28. {
  29. $this->request->setMethod(‘POST’)
  30. ->setPost(array(
  31. ’email’ => ‘regularuser@nowhere.com’,
  32. ‘password’ => ‘usertests’,
  33. ));
  34. $this->dispatch(‘/user/login’);
  35. $this->assertRedirect;
  36. $this->assertTrue(Zend_Auth::getInstance()->hasIdentity());
  37. }
  38. // ok, now let’s run some tests
  39. public function testGuestAccessRightsAreOk()
  40. {
  41. $this->CanAccess(‘/user/login’);
  42. }
  43. public function testLoggedInUserAccessRightsAreOk()
  44. {
  45. $this->LoginRealUser();
  46. $this->CanAccess(‘/user/logout’);
  47. }
  48. // testing where users can not go
  49. public function testGuestRestrictionsAreOk()
  50. {
  51. $this->CanNotAccess(‘/user/logout’);
  52. $this->CanNotAccess(‘/user/index’);
  53. }
  54. public function testLoggedInRestrictionsAreOk()
  55. {
  56. $this->LoginRealUser();
  57. $this->CanNotAccess(‘/user/login’);
  58. }

A simple way to test your user access rights !

Damn, I spent so much time building this, I’m happy I could find the solution ! Here’s a dojo grid working with Zend framework. I fist tried this on the view controller, but it got me nowhere :

  1. // My function that is supposed to add the
  2. // OD column to ID, it never gets fired…
  3. <script type=”text/javascript”>
  4. function getODtoID()  {  alert(“test”);   }
  5. </script>
  6. /* My grid, it’s working except get=”getODtoID” */
  7. <table id=”grid” dojotype=”dojox.grid.Grid” store=”pStore” query=”{ post_id: ‘*’}”>
  8. <thead>
  9. <tr>
  10. <th field=”status” width=”30px”>Status</th>
  11. <th width=”5em” get=”getODtoID”>OD to ID</th>
  12. </tr>
  13. </thead>
  14. </table>
  15. dojo()->enable()
  16. ->setDjConfigOption(‘parseOnLoad’, true)
  17. ->requireModule(‘dojo.parser’)
  18. ->requireModule(‘dojo.data.ItemFileReadStore’)
  19. ->requireModule(‘dojox.grid.Grid’)
  20. ->requireModule(‘dojox.grid._data.model’);
  21. ?>

The problem was that I couldn’t get the function getODtoID to be executed. I wanted to build a link on my grid, and for that I needed some very basic calculation. So what’s the solution ? I still can’t figure out why it’s not working this way, but I tryied something else :

  1. <script type=”text/javascript”>
  2. var customColumn = function(inRowIndex) {
  3. // This is standard for many grid handlers
  4. if (! dijit.byId(‘grid’).model.data[inRowIndex]) {
  5. return;
  6. }
  7. return “<a href=\”/blogmanager/edit?id=” +
  8. model.getRow(inRowIndex).post_id + “\”>edit</a>”;
  9. }
  10. var view = {
  11. cells:  [[
  12. { name: “Post id”, field: “post_id” },
  13. { name: ‘Link’, get: customColumn }
  14. ],
  15. ]};
  16. var layout = [ view ];
  17. </script>
  18. <div dojotype=”dojox.grid.data.DojoData” jsid=”model” store=”pStore” query=”{ post_id: ‘*’ }” clientsort=”true”></div>
  19. <div id=”grid” dojotype=”dojox.Grid” model=”model” structure=”layout”></div>
  20. dojo()->enable()
  21. ->setDjConfigOption(‘parseOnLoad’, true)
  22. ->setDjConfigOption(‘isDebug’, true)
  23. ->requireModule(‘dojo.parser’)
  24. ->requireModule(‘dojo.data.ItemFileReadStore’)
  25. ->requireModule(‘dojox.grid.Grid’);
  26. ?>

And that’s working fine, fine fine. So now it’s easy to build custom cells withing your grids !

Here’s a new problem : I want to be able to send mails using a template system. I use this for registration purepose mostly (email account confirmation, registration, etc.). Here’s a function that does this with Zend_Mail :

  1. public function sendEmail($arguments)
  2. {
  3. // Get the template arguments
  4. $template  = $arguments[‘template’];
  5. $subject  = $arguments[‘subject’];
  6. $templatearguments = $arguments[‘templateArguments’];
  7. // build a view
  8. $view = new Zend_View;
  9. $view->setScriptPath(Zend_Registry::get(‘config’)->email->folder);
  10. // Assign each item
  11. foreach($templatearguments as $k => $v){
  12. $view->assign($k, $v);
  13. }
  14. // render the template
  15. $body = $view->render($template);
  16. // Send the password by mail ;
  17. // NOTE : the message is in the $body variable (in the mail)
  18. $mail = new Zend_Mail();
  19. $mail->setBodyText($body)
  20. ->setFrom(“me@fromme.com”,”Z”)
  21. ->addTo($this->email)
  22. ->setSubject($subject);
  23. $transport = new Zend_Mail_Transport_Smtp(“my.smtp.server.com”);
  24. $logger = Zend_Registry::get(‘logger’);
  25. // Try to send the email, or log the exception
  26. try
  27. {
  28. $mail->send($transport);
  29. $logger->notice(“mail sent to ” . $this->email);
  30. }
  31. catch (Exception $e)
  32. {
  33. $logger->warn(“Error sending mail “. $e->getMessage());
  34. }
  35. }

Ok, so how would I use this ? First set up the arguments, and then use the function…

  1. $emailarguments = array(‘template’ => ‘userRegistrationEmail.phtml’,
  2. ‘subject’  => ‘Account creation’,
  3. ‘templateArguments’ => array(‘uid’ => $user->Id(),
  4. ‘key’ => $user->key,
  5. ’email’=> $user->email)
  6. );
  7. // ok done, now send the mail
  8. sendEmail($emailarguments)

Let’s find out how to format the mail, well simply like this :

  1. $body = “\n Dear user,”;
  2. $body .= “\n”;
  3. $body .= “\nThank you for your registration.  :”;
  4. (…)
  5. $body .= “\nWeb Site Administrator”;
  6. echo $body;

Ok, in the wonderfull world of PhpUnit tests I wanted to test a user registration process with Captcha enabled. But, what do you put in the Captcha field since it’s an automated test ? Well, reading the session appears to be the simplest way to get this information. Here’s a simple function I wrote, suggested by Matthew Weier O’Phinney, that will allow you simply to get the Captcha word while in your php tests :

  1. private function testGetCaptcha()
  2. {
  3. $this->dispatch(‘/user/registration’);
  4. foreach ($_SESSION as $key=>$value)
  5. {
  6. if(ereg(“Zend_Form_Captcha.*”, $key))
  7. return  $value[‘word’];
  8. }
  9. }

And here you go… It’s a quick and dirty solution since this will only work if you have a unique Zend_Form_Captcha to test for. Feel free to write a better solution !