Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

including external library in Yii

How can I call these library functions from anywhere in my Yii app? I have a library:

#mylib.php

<?php
class MyLib {
    public function foo()
    {
        echo "hello!";
    }
}

and want to be able to call this function throughout my Yii app:

MyLib::foo();

I don't know where to place my library or how/where to import it. This is just an example of what I'm trying to do but I am trying to make a library that has multiple namespaces so I can access the library and have access to all the namespaces after importing it.

like image 904
user740521 Avatar asked Dec 27 '11 20:12

user740521


4 Answers

There are several ways.

  1. Register libraries' autoloader:

    // Enable Zend autoloader
    spl_autoload_unregister(array('YiiBase', 'autoload')); // Disable Yii autoloader
    Yii::import('site.common.lib.*'); // Add Zend library to include_path
    Yii::import('site.common.lib.Zend.Loader.Autoloader', true); // Require Zend autoloader
    spl_autoload_register(array('Zend_Loader_Autoloader', 'autoload')); // Register Zend autoloader
    spl_autoload_register(array('YiiBase', 'autoload')); // Register Yii autoloader
    
  2. Add library to the import section in your config/main.php:

    return array(           
        // Autoloading
        'import' => array(
            'application.lib.*',
            'application.components.*',
            'site.common.extentions.YiiMongoDbSuite.*',
        ),
    );
    
  3. Autoloading anywhere in your application:

    Yii::import('application.lib.*');
    
like image 126
Oleg Avatar answered Sep 23 '22 16:09

Oleg


Place your library in the vendors folder (under protected folder) supposing (all your classes are in MyLib folder) you do like this:

Yii::import('application.vendors.MyLib.*');
like image 20
amez Avatar answered Sep 22 '22 16:09

amez


Explained right here: http://www.yiiframework.com/doc/guide/1.1/en/extension.integration

like image 41
Boaz Rymland Avatar answered Sep 25 '22 16:09

Boaz Rymland


I use Yii's own autoloader;

    //include auto loader class of vendor
    require dirname(__FILE__).'/mollie-api-php/src/Mollie/API/Autoloader.php';
    //Now register vendor autoloader class to Yii autoloader 
    Yii::registerAutoloader(array('Mollie_API_Autoloader','autoload'));
like image 43
Daantje Avatar answered Sep 23 '22 16:09

Daantje