Read the latest web development and design tips at Fred Wu's new blog! :-)
Poke me on GitHub

Using Zend Framework with CodeIgniter

If you ever wanted to integrate CodeIgniter and Zend Framework, you might have come across this tutorial by Daniel Vecchiato.

Whilst Daniel has done a great job demonstrating the possibility of using the two frameworks together, concerns have been made: do we actually need to use hooks?

As I understand it, hooks are used to extend the core functionalities of CodeIgniter (as explained in the user guide). Obviously Zend Framework and CodeIgniter are two different systems and there is no intention for us to extend CodeIgniter’s core functionality with Zend Framework.

Using hooks can be dangerous as it’s system-wide, and it modifies the system behaviour.

What I have done is to simply use CodeIgniter’s library structure to load the Zend Framework resources. Below is the tutorial.

Assuming you already have CodeIgniter installed. If not please refer to the user guide for installation.

  1. Download Zend Framework from the official website.
  2. Unzip the Zend Framework package, and copy the Zend folder (under Library) to your CodeIgniter installation’s application/libraries/. You can actually place the folder anywhere, but remember to alter the script accordingly (read the comments in the script!).
  3. Place the library script (provided at the end of the post) in application/libraries/
  4. Done! That’s all you need to do. Now, let us see an example of using the library.

Usage Sample

<?php

class Welcome extends Controller {

	function Welcome()
	{
		parent::Controller();
	}

	function index()
	{
		$this->load->library('zend', 'Zend/Service/Flickr');
		// newer versions of CodeIgniter have updated its loader API slightly,
		// we can no longer pass parameters to our library constructors
		// therefore, we should load the library like this:
		// $this->load->library('zend');
		// $this->zend->load('Zend/Service/Flickr');

		$flickr = new Zend_Service_Flickr('YOUR_FLICKR_API_KEY');

		$results = $flickr->tagSearch('php');
		foreach ($results as $result)
		{
			echo $result->title . '<br />';
		}
		//$this->load->view('welcome_message');
	}
}
?>

Library Script

Copy the code and paste it to a new file called Zend.php in application/libraries/.

<?php if (!defined('BASEPATH')) {exit('No direct script access allowed');}

/**
 * Zend Framework Loader
 *
 * Put the 'Zend' folder (unpacked from the Zend Framework package, under 'Library')
 * in CI installation's 'application/libraries' folder
 * You can put it elsewhere but remember to alter the script accordingly
 *
 * Usage:
 *   1) $this->load->library('zend', 'Zend/Package/Name');
 *   or
 *   2) $this->load->library('zend');
 *      then $this->zend->load('Zend/Package/Name');
 *
 * * the second usage is useful for autoloading the Zend Framework library
 * * Zend/Package/Name does not need the '.php' at the end
 */
class CI_Zend
{
	/**
	 * Constructor
	 *
	 * @param	string $class class name
	 */
	function __construct($class = NULL)
	{
		// include path for Zend Framework
		// alter it accordingly if you have put the 'Zend' folder elsewhere
		ini_set('include_path',
		ini_get('include_path') . PATH_SEPARATOR . APPPATH . 'libraries');

		if ($class)
		{
			require_once (string) $class . EXT;
			log_message('debug', "Zend Class $class Loaded");
		}
		else
		{
			log_message('debug', "Zend Class Initialized");
		}
	}

	/**
	 * Zend Class Loader
	 *
	 * @param	string $class class name
	 */
	function load($class)
	{
		require_once (string) $class . EXT;
		log_message('debug', "Zend Class $class Loaded");
	}
}

?>

Happy coding! Oh and don’t forget, Zend Framework is PHP 5 only, so it won’t work on your PHP 4 installation.

Update: Using it with Kohana

Update: The following instructions are deprecated, please follow the updated one here.

Even though Kohana has the ability to load vendor classes, I still find it useful to use the library approach so that loading Zend Framework libraries will be transparent. :)

Usage is exactly the same as in CodeIgniter.

<?php defined('SYSPATH') or die('No direct script access.');

/**
 * Zend Framework Loader
 *
 * Put the 'Zend' folder (unpacked from the Zend Framework package, under 'Library')
 * in CI installation's 'application/libraries' folder
 * You can put it elsewhere but remember to alter the script accordingly
 *
 * Usage:
 *   1) $this->load->library('zend', 'Zend/Package/Name');
 *   or
 *   2) $this->load->library('zend');
 *      then $this->zend->load('Zend/Package/Name');
 *
 * * the second usage is useful for autoloading the Zend Framework library
 * * Zend/Package/Name does not need the '.php' at the end
 */
class Zend
{
	/**
	 * Constructor
	 *
	 * @param	string $class class name
	 */
	function __construct($class = NULL)
	{
		// include path for Zend Framework
		// alter it accordingly if you have put the 'Zend' folder elsewhere
		ini_set('include_path',
		ini_get('include_path') . PATH_SEPARATOR . APPPATH . 'libraries');

		if ($class)
		{
			require_once (string) $class . EXT;
			Log::add('debug', "Zend Class $class Loaded");
		}
		else
		{
			Log::add('debug', "Zend Class Initialized");
		}
	}

	/**
	 * Zend Class Loader
	 *
	 * @param	string $class class name
	 */
	function load($class)
	{
		require_once (string) $class . EXT;
		Log::add('debug', "Zend Class $class Loaded");
	}
}

?>
  • Digg
  • DZone
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • LinkedIn
  • Live
  • Reddit
  • Slashdot
  • StumbleUpon
  • Technorati
  • Twitter

Related posts

Tags: , , , ,

Comments Section

52 Responses to “Using Zend Framework with CodeIgniter”

Sidebar might be covered by comments ... consider it a feature! ;)
  1. 3

    Hi Fred, thanks for this helpful article. I have a few noobesque questions for you about the library file:
    1. do you check for the BASEPATH because that is just part of how you handle security or is that required by CI (or both)?
    2. in line 31 is APPPATH a constant that is defined somewhere in Code Igniter?
    3. In line 35 and 51 what is EXT?
    4. that bit about (string) on lines 35 and 51… is that an example of casting? Is that for security?
    5. In lines 33-41 is that checking for the class just so you can log for your own convenience or is there another reason?
    6. Why do you need the load() function? Seems like you take care of it (or could) in the constructor.

    Thanks for your time!

  2. 4

    Hi Stuart, to answer your questions:

    1. Yes BASEPATH checking is required in CI to ensure users don’t accidentally access the library file itself directly. (remember, library files are meant to be called in your models/controllers)

    2. APPPATH is defined in index.php which is in the root folder of your CI distribution.

    3. EXT is another constant defined in the above mentioned file, it is used to echo the php file extension, usually ‘.php’.

    4. Yes it is type casting, for added security measurement and code clarity (and in this case it’s more of code clarity).

    5. Log class is one of the core classes provided by CI. By logging crucial events it offers better assistant for debugging purposes.

    6. As demonstrated in the code comment section, there are two ways of calling the library, one is by calling it with a second parameter which will call the specific Zend component straight away, or you can omit the second parameter and use ‘$this->zend->load()’ later one, useful for autoloading the library.

    Hope that helps. :)

  3. 7

    what about integration with ez components?

  4. 8

    You can use these tags:

  5. 11

    While this solution works with your example, I have found that if there are Zend classes that have dependencies, which are most (i.e. delicious service), then you have to load all the dependent classes as well as the one you intend to use.

  6. 12

    I used to prefer to create a vendor folder, upload my Zend file, and stick this in the index.php file:

    define(‘DOCROOT’, getcwd().DIRECTORY_SEPARATOR);
    ini_set(‘include_path’,ini_get(‘include_path’) . ‘.’ . PATH_SEPARATOR . DOCROOT . ‘vendor/’);

    then execute my zend scripts accordingly.

    but I prefer your method… it ties everything together beautifully – great job!

  7. 16

    Thanks for providing this code. I’ve been pulling my hair out tonight looking for a good way to integrate ZF into Kohana. I noticed that $this->load is apparently depricated. So I tried to do everything the same way you described, except replaced the $this->load lines with:

    $z = new Zend;

    Of course I want to use Zend_Db … so then I started trying to do stuff like…

    require_once(‘Zend/Db’);

    Not working… Any ideas on how to adapt this to the changes in Kohana? Also, thought I’d note I had to comment out the Log:: lines in the Zend.php. Looks like they broke those too.

    Cheers,
    Chris

  8. 17

    @Chris: Make sure you include the file extension, e.g. ‘Zend/Db.php’.

    The ‘Log’ class is superseded by ‘Kohana::log’.

  9. 19

    I have posted new instructions for Kohana here: http://www.beyondcoding.com/20.....deigniter/

  10. 20

    Hi Fred, thanks for this article. I too prefer the use of libraries instead of hooks.

    I’m using Zend’s class loader instead of the load function you provide in CI_Zend. So, for example, to use the Gdata Calendar classes I do the following:

    1) Load library and Loader class from it: $this->load->library(‘zend’, ‘Zend/Loader’);
    2) Load Zend libraries:
    Zend_Loader::loadClass(‘Zend_Gdata’);
    Zend_Loader::loadClass(‘Zend_Gdata_ClientLogin’);
    Zend_Loader::loadClass(‘Zend_Gdata_Calendar’);

    Everything runs ok. Do you know which method is better (the load function or Zend’s loader? Thanks.

  11. 22

    @fbm: From the Zend Framework user guide:

    Zend_Loader vs. require_once()

    The Zend_Loader methods are best used if the filename you need to load is variable. For example, if it is based on a parameter from user input or method argument. If you are loading a file or a class whose name is constant, there is no benefit to using Zend_Loader over using traditional PHP functions such as require_once().

  12. 25

    I’ve been looking for something like this for years, this is awesome!!!

  13. 26

    Please help me.
    how can I using PHPExcel with codeigniter??

  14. 27

    I use this trick to load other libraries like jabber which needs to pass arguments when instantiating. Nice tutorial.

  15. 28

    i tried the solution here, but when i try to use Zend::Session and Zend::AMF together, it won’t work. any ideas? AMF stops transmitting, when Session gets attached. But Zend’s own page says AMF supports Sessions.

  16. 33

    Hey. First of all thanks for all your work making life for newbies much easier. One question I have to do as I am really newbie with this stuff, first days with both frameworks (codeigniter and zendstudio) I didnt understand quite well exactly which es de Library folder of the ZEND, i’ve searched inside the installation and found several Library directories (ex: \plugins\com.zend.php.phpunit_7.0.0.v20090708-1507\resources ; \plugins\org.zend.php.framework.resource_7.0.0.v20090531-1639\resources\ZendFramework-1)

    What I’ve done also and think is wrong has been installing completely the Zend Studio framework inside the CodeIgniter installation’s application/libraries/ because i first understood it was the thing to do.

    Can you tell me exactly tell me which ZEND studio Library directory has to be copied inside the application/libraries of CODEigniter, and assure me that the installation of ZEND studio has to be under Program files or else directory and not making CODEigniter the container folder for all the ZEND framework???

    thanks for your help

  17. 34

    Hi,

    Thanks for the wonderful Example. Is there any sample code for Smarty and Zend Framework?

    Dan

  18. 35

    It’s a very good job, keeps everything tidy and nice. Thanks

  19. 36

    I get the following error message.
    Can anyone tell me what’s wrong please?

    +++++++++

    A PHP Error was encountered

    Severity: Warning

    Message: require_once(Zend/Validate/Between.php) [function.require-once]: failed to open stream: No such file or directory

    Filename: Service/Flickr.php

    Line Number: 476
    ++++++
    Fatal error: require_once() [function.require]: Failed opening required ‘Zend/Validate/Between.php’ (include_path=’.:/usr/local/php5-suphp/lib/php:/home/1/o/mywebsite/www/ci/system/libraries’) in /home/1/o/mywebsite/www/ci/system/application/libraries/Zend/Service/Flickr.php on line 476

  20. 40

    In my case the PHP include path contained an old version of Zend so to avoid updating it the Zend files in the CodeIgniter libraries folder had to be loaded first.

    I altered:
    ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . APPPATH . 'libraries');

    To:
    ini_set('include_path', APPPATH . 'libraries' . ':' . ini_get('include_path'));

    Thanks for the library very useful!

  21. 41

    My saviour man.
    Search and ye shall find indeed.

    Great tutorial — saved me an good hour.

  22. 43

    For anyone who is interested – I’ve posted up a project starter on my blog – a dev ready incorporation of the following technologies:

    - ExtJS : client side JS library,
    - CodeIgniter : presentation + domain tier,
    - Doctrine : ORM data layer framework

    Some features of this project starter are:
    - CodeIgniter Models have been replaced with Doctrine Records
    - Doctrine is loaded into CI as a plugin
    - RoR type before and after filters….
    - Doctrine transactions automatically wrapped around every action at execution time (ATOMIC db updates)

    Basic Role based security (I think Redux may be in there as well?)
    Simply extract, hook up the database.php config file and viola…. You can start coding your layouts, views and models. Probably a few things to iron out – but enjoy!

    Hope it helps

    GET IT AT: http://thecodeabode.blogspot.c.....extjs.html

  23. 45

    When I follow these directions, I get PHP fatal errors telling me that whatever Zend class I try to load cannot be redeclared. Any advice on where to look to troubleshoot?

Trackbacks

  1. Zend Framework: The Best Framework for Use With Other Frameworks
  2. Developer Tutorials Blog: Zend Framework: The Best Framework for Use With Other Frameworks | Development Blog With Code Updates : Developercast.com
  3. Glagla Dot Org - Olivier Mansour » Pensez à intégrer Zend Framework dans votre framework habituel ?
  4. 將 Zend Framework 放進 CodeIgniter « Oceanic | 人生海海
  5. 將 Zend Framework 放進 CodeIgniter | 学而.海口 [X Education.HaiKou]
  6. links for 2008-05-22 | the sweetview blog
  7. links for 2008-09-08 | daha iyi net
  8. Dropdown Country List with Code Igniter and Zend Framework « Momgeek’s Weblog
  9. 將 PEAR 放進 CodeIgniter | ::SANKAI::
  10. Using Zend Framework with Kohana | Beyond Coding
  11. PHP-ist: All about learning PHP, frameworks, tips and tricks » Kohana and Zend, Killer Combo! The best PHP5 framework and library in one package.
  12. 【转】將 PEAR 放進 CodeIgniter « LEMON’s BLOG - 黎明博客
  13. CodeIgniter with Zend Framework Libraries | gotPHP
  14. CodeIgniter Suchmaschine mit Lucene aus dem Zend-Framework von Benjamin Mock
  15. How to use Zend_Search_Lucene with the PHP framework CodeIgniter « C.M. Jackson
  16. Usando os componentes do Zend Framework no CodeIgniter | Gostei
  17. Usando os componentes do Zend Framework no CodeIgniter | Bruno Alves
  18. Okada Design Blog » Blog Archive » How to implement Zend Framework with Codeigniter on Windows
  19. Authlite 2.0 for Kohana 3.0 Alpha Testing « Best PHP Frameworks
  20. 使用Library方式將Zend Framework整合到CodeIgniter « 通往幸福的部落
  21. CodeIgniter + Zend Library + Doctrine = doCEND | fclose
  22. Adding Zend Library to CodeIgniter - by choice, not by chance
  23. How to use Zend Framework in CodeIgniter 2.0 | Yodi Aditya
  24. How to use Zend Framework in CodeIgniter 2.0 | Yodiaditya Codeigniter Research
  25. Extensibilidade
  26. Zend Barcodes in CodeIgniter | The Ghostbilt Blog
  27. Zend Framework & CodeIgniter | Matrix Coder
  28. Zend Barcodes in CodeIgniter | Japheth Benfield
  29. Некоторые полезности | coder.davinci-design.ua

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>