coding >> A better Zend Framework & Smarty integration (4,170 views)

Table of contents for Zend Framework

  1. Zend Framework and Smarty integration
  2. A better Zend Framework & Smarty integration
  3. Zend_Layout example

Since the first post on this series I have been working with the Zend Framework and Smarty extensively and I have greatly improved my previous integration between Smarty template engine and ZF.

I have prepared and example that you can download from the following link:
zend.zip (3.5 MB) the compressed file includes the ZF and Smarty packages.
The zip file should unpack as follow:

  • Zend
    • application
      • bootstrap.php
      • config.php
      • include
        • CustomControllerAction.php
        • SmartyView.php
      • lib
        • Smarty-2.6.20 // the smarty library
        • Zend // the ZF library
      • models
      • modules
        • admin
          • IndexController.php
        • default
          • IndexController.php
      • views
        • admin
          • footer.tpl
          • header.tpl
          • index
            • index.tpl
        • default
          • footer.tpl
          • header.tpl
          • index
            • index.tpl
        • templates_c
    • htdocs
      • css
        • style.css
      • images
      • index.php
      • .htaccess
    • access_log
    • error_log

The structure is such that the htdocs directory should be your document root as in the following virtual server configuration:

<VirtualHost *:80>
	ServerName zend
	DocumentRoot /var/www/zend/htdocs
	CustomLog "/var/www/zend/access_log" "combined"
	ErrorLog "/var/www/zend/error_log"
	<Directory /var/www/zend/htdocs>
		Options Includes FollowSymLinks
		AllowOverride All
	</Directory>
</VirtualHost>

Also i have added zend (ServerName) in my hosts file (on linux /etc/hosts) so that from the browser (firefox) i can just type http://zend/.
Remember to make the templates_c writeable by the web server, smarty will compile in there the template files.

The Smarty ZF integration is done in 2 steps:
First I extended the Zend_View_Abstract class with the class called SmartyView in the SmartyView.php file, I have overwritten the magic methods, in particular the very useful __set so that from our controllers we can just do $this->view->name = "value"; which will be equivalent of having smarty->assign("name", "value").
The second step is to tell the controllers to use our SmartyView class rather then the default Zend_View class and this is done with with the following code written in the bootstrap.php file:

1
2
3
4
5
6
7
8
$vr = new Zend_Controller_Action_Helper_ViewRenderer();
// important when developing using modules, so you can have various modules,
// for example an admin module, an e-commerce module and the default module
$vr->setViewScriptPathSpec(":module/:controller/:action.:suffix");
// integrate smarty with Zend Framework
$vr->setView(new SmartyView());
$vr->setViewSuffix('tpl');
Zend_Controller_Action_HelperBroker::addHelper($vr);

Note that line 4 is not related with smarty/ZF integration, but is needed to be able to use modules.

Acknowledgement:
my knowledge of the Zend Framework leaped forward after reading the excellent book by Quentin Zervaas titled “Practical Web 2.0 Applications with PHP”.


Leave a Comment or Trackback from your own site.

14 Responses to “A better Zend Framework & Smarty integration”

  1. zendrej says:

    Hello Andrea,

    I am a beginner in using Zend Framework.
    I must appreciate the way you have shared your knowledge in such a simple way… it is good for a fresher like me.

    Sorry i could not at all download your example, second i am getting the below error when i try to run your code.

    “..
    Fatal error: Function name must be a string in C:\wamp\www\zendsmarty\Smarty\Smarty.class.php on line 1524 ..”

    I must have made a mistake, can you please help me out ?

    rgds,
    rej

  2. Hi rej,
    Thanks for your comment,
    here is the direct link to the code of this post example: http://www.andreabelvedere.com/download/zend.zip it should work.

    About the error you are getting I need a bit more info to be able to help you;
    I can see the directory structure you are using is different from the download-able example,
    which controller and what code are you hitting with your request ?

    Also I am a bit confused as you are saying that you couldn’t download my example but you are running my code, which code ?

  3. zendrej says:

    Hi Andrea,

    Thanks for your reply.

    Sorry, i had copied the code given in the first link “Zend Framework and Smarty integration” and run the same. Even the zend.zip file i tried to download was from the same page. I should have tried from “A better Zend Framework & Smarty integration”.

    Now it is working fine. Thanks a lot for your attention.

    Regards,
    Rej

  4. zendrej says:

    Hello Andrea,

    I have zend framework running with my wamp server. Pear is installed before i started using zend framework. Do you have an idea how i can use pear with zend framework ?

    Thanks,
    Rej

  5. Hi Rej,
    Pear and ZF are totally compatible, (as they both use the same name convention) in fact using ZF autoload:

    require_once "Zend/Loader.php";
    Zend_Loader::registerAutoload();

    you will be able to use pear classes without requiring or including them, just make sure the pear directory is in your php classpath.
    hope it help.

  6. zendrej says:

    Thank you Andrea.

    I will try out an example and come back to you.

    Thanks a ton for replying.

    regards,
    rej

  7. Alfonso says:

    Great tutorial!

    I have a couple questions tho. I currently have a site running on smarty, but the way I use it, well it’s different. I like it tho. I’ve been trying to modify your code to get it to work but not sure if i can. Not to experienced with Zend so here it goes.

    I want to have a wrapper file that gets included on every action. Now, I have a tag in the wrapper called {$body}. This tag gets replaced by the file that the current template is associated with. So for example I would like to have this done….

    http://www.example.com/members/view

    I would like the wrapper to be included but the file in the /views/default/members/view.tpl be included in as an {include file=???}

    Is there a way I can do this? Still reading up on Zend so please bare with me.

  8. nicolas says:

    hey Andrea, need your help again after i experience fatal error in section 1 of your tutorial, now it happen again in section 2 as below:
    Catchable fatal error: Argument 1 passed to
    Zend_Config::__construct() must be an array, integer given, called in
    C:\xampp\htdocs\zend\application\bootstrap.php on line 23 and defined
    in C:\xampp\htdocs\zend\application\lib\Zend\Config.php on line 98

  9. Krack says:

    Hellodo you changerequire_once "Zend/Loader.php";
    Zend_Loader::registerAutoload();
    to require_once “Zend/Loader/Autoloader.php”;$autoloader = Zend_Loader_Autoloader::getInstance();$autoloader->setFallbackAutoloader(true);

  10. I just couldnt leave your web site before saying that I truly enjoyed the quality information you provide for your visitors. Will be back generally to check up on new information in you article!

  11. Pravin says:

    Hello,  You site is greate. I have download the code and put that folder in c:/wamp/www folder and run it in browser then they give following error : Warning: require_once(Zend/Loader.php) [function.require-once]: failed to open stream: No such file or directory in C:\wamp\www\zend\application\bootstrap.phpon line 21Fatal error: require_once() [function.require]: Failed opening required ‘Zend/Loader.php’ (include_path=’.;C:\php5\pear;C:/wamp/application/lib;C:/wamp/application/models;C:/wamp/application/include;’) in C:\wamp\www\zend\application\bootstrap.phpon line 21Please sugest.

  12. Hi Pravin,
    That error means that the Zend folder is not in your include path.
    so the line:
    require_once 'Zend/Loader.php';
    fails as the Loader.php file is not found.
    Make sure the Zend folder is in your include path. The bootstrap.php file attempts to include the Zend folder in the include path with the lines:

    // Set our include path
    $include_path = get_include_path().PATH_SEPARATOR;
    $include_path .= SITE_ROOT.'/application/lib'.PATH_SEPARATOR;
    $include_path .= SITE_ROOT.'/application/models'.PATH_SEPARATOR;
    $include_path .= SITE_ROOT.'/application/include'.PATH_SEPARATOR;
    set_include_path($include_path);

    however for the lines above to work the SITE_ROOT defined variable must be correctly set, which means that in your case this:
    dirname($_SERVER['DOCUMENT_ROOT'])
    should return the following:
    C:\wamp\www\zend
    but in your case is returning:
    C:\wamp\

    So to make it work correctly you have the following options:
    1) change your “DocumentRoot” in your apache configuration file, or VirtualHost block to point to C:\wamp\www\zend\htdocs so it should be DocumentRoot C:/wamp/www/zend/htdocs
    or
    2) change this line in the bootstrap.php file, from:
    define("SITE_ROOT", dirname($_SERVER['DOCUMENT_ROOT'])); to
    define("SITE_ROOT", "C:/wamp/www/zend");

    hope it helps
    andrea

  13. Jules says:

    Hi Andrea Thanks for this usefull method,it’s appear that i’ve a problem<code>Fatal error: Uncaught exception ‘Zend_Controller_Dispatcher_Exception’ with message ‘Invalid controller specified (admin)’ in ..</code>unfortunately i don’t see any problem in my Bootstrap and i use the modular structure.If i create an AdminController in the folder /controllers under /app i see a new message ‘admin.phtml not found’What is really strange is that all the smarty template as described as you works great.Is someone see what kind of problem it is ?many thanks

  14. Kelly says:

    thanks for this article, I was able to adapt it quite quickly to my codebase. I also enjoy the aforementioned book, although I started it, I ended up taking a step back to get some more fundamentals under my belt first and now am just coming back to zend framework. I would reccommend to anyone starting out with a php from novice to professional type book, then going to something for zend framework.  

Leave a Reply