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.
There are several ways.
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
Add library to the import section in your config/main.php:
return array(
// Autoloading
'import' => array(
'application.lib.*',
'application.components.*',
'site.common.extentions.YiiMongoDbSuite.*',
),
);
Autoloading anywhere in your application:
Yii::import('application.lib.*');
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.*');
Explained right here: http://www.yiiframework.com/doc/guide/1.1/en/extension.integration
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'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With