Integrating ZF2 into Yii - use case demonstrated

  1. General
  2. Recipe

General

I needed to use a class from ZF2 in my Yii project. I've read probably all there is about this subject and still I needed lots of trial & errors to get it working, probably due to my lack of experience working with namepsaces and ZF2 in general. Also, the resources on the web are all partial, at best. Most simply refer to ZF1 where things are technically different. When I got it all working I decided to record my findings and that's how this article was born. The below recipe is what worked for me, accompanied by relevant comments. References: This article is partially based on this guide page. Be sure also to consult Zend Framework 2 documentation.

In my case I was required to use Zend/Feed/Reader class to consume and parse feeds from the web. This is what's demonstrated below.

Recipe

1) Unpack ZF2 (v2.2.0 was tested in my case) somewhere in a temporary location on your disk (typically /tmp).

2) Copy recursively library/Zend directory from the unpacked tree (resuresivly) to protected/vendors/ (the end result should be /protected/vendors/Zend/...). The target location is important and (probably) cannot be altered. Why? Since to the best of my understanding the loading of classes in ZF2 will be handled by Yii but the only thing that makes this possible is the adherence of both to psr-0 (the "PHP standard recommendation" that deals with autoloading standardization).

3) Before using ZF2 classes you need to do the following couple of statements:

(A) The following will effectively alter the 'php include path' to add any directory with 'applications.vendors' as a valid include-path directory.

Yii::import('application.vendors.*');

(B) The following code will set a 'path alias' named 'Zend' to point to the ZF2 library root. Again, I presume it is needed in order to enable the psr-0 autoloading magic, and in specific to enable Zend classes to be called when needed, as dependency inside ZF2 requires.

Yii::setPathOfAlias('Zend',Yii::getPathOfAlias('application.vendors.Zend'));

4) Last step - use the actual needed class. I needed to fully qualify the namespace of the Reader class, but that's a PHP thing and stems from how PHP resolves namespaces, I guess:

$reader = Zend\Feed\Reader\Reader::import('http://example.com/path/to/feed.xml');

That's it! Now $reader contains a Reader object and also along the way other ZF2 classes where instantiated (this was verified in il-attempts to get it working which resulted in PHP errors about ZF2 classes not found...).

4 0
6 followers
Viewed: 11 222 times
Version: 2.0
Category: How-tos
Written by: Boaz
Last updated by: Boaz
Created on: Jun 9, 2013
Last updated: 6 years ago
Update Article

Revisions

View all history