Tuesday, July 3, 2012

how import and autoloading works in YII

1. Let's assume that we have a custom class named LyricsFinder that finds lyrics
for a given song. We have put it under protected/apis/lyrics/ and in our
protected/controllers/TestController.php, we are trying to use it in
the following way:
class TestController extends CController
{
public function actionIndex($song)
{
$lyric = 'Nothing was found.';
$finder = new LyricsFinder();
if(!empty($song))
$lyric = $finder->getText($song);
echo $lyric;
}
}
2. When executing it, we will get the following PHP error:
include(LyricsFinder.php) [<a href='function.include'>function.
include</a>]: failed to open stream: No such file or directory.
3. Yii helps us there a bit because at the error screen, we can see that autoloader fails
because it doesn't know where to look for our class. Therefore, let's modify our code:
class TestController extends CController
{
public function actionIndex($song)
{
$lyric = 'Nothing was found.';
// importing a class
Yii::import('application.apis.lyrics.LyricsFinder');
$finder = new LyricsFinder();
if(!empty($song))
$lyric = $finder->getText($song);
echo $lyric;
}
}

No comments:

Post a Comment