Loading custom classes in CodeIgniter? - php

Just starting to use CodeIgniter, and I'd like to import some of my old classes for use in a new project. However, I don't want to modify them too much to fit into the CI way of doing things, and I'd like to be able to continue to use NetBeans' autocomplete functionality, which doesn't work too well with CI.
So, what is the best way to load custom classes & class files into CodeIgniter without having to use the library/model loading mechanisms?
I apologise if this is something I should be able to find quickly, but I can't seem to find what I'm after. Everything I see is just telling me how to go through CI.

To do it codeigniter way, place your custom classes in libraries folder of codeigniter. And then use it by adding that class as library in your controller like this:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Someclass {
public function some_function()
{
}
}
/* End of file Someclass.php */
using in controller:
$this->load->library('someclass');
checkout complete article at http://www.codeigniter.com/user_guide/general/creating_libraries.html

Libraries are easy to write but they have a few restrictions. Constructors can only take an array as a parameter and it's assumed that only one class will exist per file.
You can include any of your own classes to work with them however you want, as this is only PHP ofc :)
include APPPATH . 'classes/foo.php';
$foo = new Foo;
Or set up an __autoload() function in your config.php (best place for it to be) and you can have access to your classes without having to include them.

I'd say you at least write a wrapper class that could require the classes and instantiate the objects and make them accessible. Then you could probably autoload such library and use it as needed.
I would recommend that you at least tried to have them fit in the CI way, as moving forward this will make you life much more easy. I've been in kind of the same position and learned just this along the way.

require_once(PHYSICAL_BASE_URL . 'system/application/controllers/abc.php');
$report= new abc();
Next use the function detail in abc contoller:
$mark=$report->detail($user);

If you're just starting to use CodeIgniter, maybe you ought to check Kohana (http://kohanaframework.org/). It is very similar to CodeIgniter in many ways but it loads classes in the normal way (using new ClassName()) so Netbeans' autocompletion features should works normally.

Related

Curiosity: Will too much autoload in codeigniter make application slower?

I'm using php and codeigniter, It has autoload class.
My first question is,
If I use autoload class to load all model will it make my application slower? Or is there no effect?
My second question :
Which one is better and faster, loading all model you need using autoload class, Or load only some models you need in a class function?
1) Autoload class will obviously make your application slower. because it uses php4 require function to load files. there are some hacks to use php 5 autoloading feature. Hope, new owner of codeigniter will add add support for autoloading.
2) It is best to use load specific models rather than autoload. in previous point I stated the reason behind this. basically it is good practice to load only the needed model, helper, library and assets. it assures that you use minimum time and memory.
I use autoload. and its working like a charm with no significant impact on loading time.
Method
Add this peace of Code on top of any libraries/models that you use in you CI autoload.php
example for me my config/autoload.php looks like
$autoload['libraries'] = array('database','door','acl','form_validation','notify');
and in libraries/Door.php i added
<?php//libraries/Door.php
function multi_auto_require($class) {
#var_dump("requesting $class");
if(stripos($class, 'CI') === FALSE && stripos($class, 'PEAR') === FALSE) {
foreach (array('objects','core') as $folder){//array of folders to look inside
if (is_file(APPPATH."{$folder}/{$class}.php")){
include_once APPPATH."{$folder}/{$class}.php";
}
}
}
}
spl_autoload_register('multi_auto_require');
class Door {
i added this snippet just above class Door{ in this way this snippet will run on every time codeigniter loads door library.
Testing and benchmarking
now For benchmarking i tested this code in a page with 17 DB queries from 8 Autoloaded Objects from 2 different folder with array of 3 folders to look in.
Result
using above mentioned method Vs include_once 'classlocation.php' for all project classes,
the average of 10 page refreshs for both methods where around 0.6sec;
so you can see there is no significant difference between both methods.
yet although i didn't test it on pages that doesn't use all class's, yet im sure autoloading makes my CI life much better and i'm happy with it.

Codeigniter Custom Libraries and Namespaces

I have been creating custom libraries for a project that i've been porting over into the CI framework and I ran into an issue where certain classes have identical names.
To circumvent this issue, I tried implementing namespaces to no avail. I've been doing research and I know in the past this may not have been possible but with the newer version of PHP, I was wondering if there was a way to do this or if I was doing it correctly.
CI Version: 2.1.4
PHP Version: 5.4.12
Here is a demo of my setup:
application/libraries/class1.php
<?
class class1{
public function __construct()
{
$CI =& get_instance();
$CI->load->library('foo/class2.php');
}
}
?>
application/libraries/foo/class2.php
<?
namespace foo
class class2{
function bar(){
}
}
?>
When I run my CI application, I will get the following error:
Non-existent class: class2
Thanks for any help.
From what I've found, if the library file doesn't have
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
as the first line of code it won't load the library.
But then the namespace declaration needs to be above that.
CodeIgniter was written for PHP4 whereas namespace is PHP5.
There's more information in this thread: Namespace in PHP CodeIgniter Framework
Codeigniter does not support namespaces in 2.x and 3.x, what I would usually do especially with 3rd party libraries is load them in manually. Using your example, I would do:
// you can still manually load in libraries like this
require_once(APPPATH.'libraries/foo/class2.php');
class class1 {
public function __construct()
{
$CI =& get_instance();
// instantiate the class2 and make it available for all of class1 methods
$this->class2 = new foo/class2();
}
}
Just because it's a framework doesn't prevent you from using core php functionality, most people forget that you can still do normal php methods to achieve the same results.
This issue arose in a personal project while attempting to use some third-party libraries.
To get around it (without modifying the source files), I made a "bootstrap" class that loaded and extended the core library:
<?php
require_once(APPPATH.'libraries/foo/class2.php');
class class2 extends foo\class2 {}
This "bootstrap" class can then be loaded and used as if it were the extended one:
$this->load->library("class2");
$this->class2->bar(); // same as foo\class2->bar();
The issue is that 'load' doesn't take into account namespaces as far as I know.
which means that load('foo/class2') will look for the folder 'foo' inside the libraries folder.
you include the files normaly, when you create a new object you use the 'foo/bar'.
I'm not if the load class supports that though, You might need to simply create a new object manually(which is what the load class does anyway, it includes the file and creates a new object).
I'll quote an answer from Alex.
I know I've answered this question before I just can't find where and don't know what to search. So here it is: Codeigniter can only load single php file libraries (excluding drivers which is a different thing entirely). To load this kindof library (namespaced) you have to use something like: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader-examples.md (class example).
Let's call it Autoloader_psr4 and save it in libraries (modify the class declaration to match this name verbatim (e.g. Autoloader_psr4). Remove the namespace declaration in the class so it looks like: https://pastebin.com/NU8Rbp7Y
Let's also move all the files in src/randomorg/ or src/foo to just be in a folder in third_party called RandomOrg or foo e.g. application/third_party/RandomOrg or application/third_party/foo. Your folder should look like the contents here: https://github.com/defiant/randomorg/tree/master/src/randomorg
Usage:
$this->load->library('autoloader_psr4');
$this->autoloader_psr4->register();
$this->autoloader_psr4->addNamespace('RandomOrg', APPPATH . 'third_party/RandomOrg');
$random = new \RandomOrg\Client(); // or whatever...

Zend General Functionality

I am learning how to use the Zend Framework. I come from a codeigniter background.
What I want to do is define a function somewhere that performs a very simple yet useful function. I am predominantly going to use the function within view scripts. I don;t really want to make a whole class for such a simple thing, so my question is, is there anywhere were can I put a file containg all of my general functions and how do I go about using it?
Thanks
John
What you are looking for are view helpers.
A view helper however is a function in a helper class. Therefore only one view helper can be put in a single class.
If you are using the project setup as used in the quick start tutorial or as generated by Zend_Tool, your view helpers should be put in the application/views/helpers directory.
Declaring a view helper is pretty simple, and is explained in great detail on this page of the zend framework documentation (i must say it's a bit hidden in the docs):
http://framework.zend.com/manual/en/zend.view.helpers.html#zend.view.helpers.custom
Some background information on view helpers as well as some standard included ones can be found on this page: http://framework.zend.com/manual/en/zend.view.helpers.html
Hope this helped you in the right direction.
If you realy whant to use a function you can make a library class with a static method , make a folder like this Application/Library/MyLib , then at bootstrap register MyLib namespace like this
$autoloader = Zend_Loader_Autoloader::getInstance();
$autoloader->registerNamespace('MyLib'); , then inside MyLib folder you can make a filename MyClass , with a class name MyLib_MyClass , then inside you're view you can call MyLib_MyClass::staticMethod().
Tough i suggest you make a view helper for this . You don't realy use functions in ZF like you where used to in CI ( i was in you're exact situation a few months ago ) , ZF is all about OOP .

Why does Codeigniter assume I want to create an instance of the class when using $this->load?

In Codeigniter, when we use $this->load('class_name') in the controller, CI will try to create an instance of the class/model using its constructor.
But sometimes, I don't actually need an instance from that class, I just want to call some static functions from it. Also, there is a big limitation with $this->load('class_name'), it does not allow me to pass parameters to the constructor (unless we extend or modify the core class of CI).
I think the $this->load('class_name') function should only do a require_once on the class php file for me, and let me freely do things (create instance/call static functions) with the class in the controller.
Should I simply ignore this function and use require_once or writing my own __autoload function to load up the classes? This way, I just feel strange because it seems I am not writing codes inside the CI box.
You can pass parameters to your constructor. See the "Passing Parameters When Initializing Your Class" section in the user guide.
I found CodeIgniter's object creation and loading to be very limiting. I want full control over my code, and little magic in the background. I have instead started using Doctrine's Class Loader. It's very lightweight and is essentially SPL autoloading (also a good alternative). You don't need the whole Doctrine shebang with ORM and all that stuff, just the ClassLoader. There's some configuration tinkering to get this right, but it works wonders.
With PHP 5.3 I now have namespaced classes in the Application directory. For instance I created a new class in the Tests directory: Application\Tests\SomeTest.php
That test could look something like this:
namespace Tests;
class SomeTest {
...
}
I would use this class in my code (controllers, views, helpers) by simply using the fully qualified namespace (i.e. $test = new \Tests\SomeTest) or a "use" statement at the top of my code (use \Tests\SomeTest as SomeTest).
In this way I intend to replace all libraries and models with OO namespaced variants. There are many benefits to this: fast autoloading with SPL, full IDE intellisense support for classes/methods (CodeIgniter is really bad for that), your code is more portable to other frameworks or projects.
That said, I still use a lot of the CodeIgniter engine. This basically means I have $CI =& get_instance() in most of my classes. It's still a work in progress and I think the main reason I need CI is for it's database access. If I can factor that out ... and use something like Dependency Injection, then I won't need CodeIgniter in my classes at all. I will simply be using it for it's MVC framework, and using it's methods occasionally in my controllers.
I know this goes above and beyond your question, but hopefully it's some food for though - and it helps me to get it in writing too.

Is there something like a macro in PHP? Or: How to make an own include function?

What I want to do is this:
When I write a class and the class instantiates another class, I want to import that class with an require_once. Just the way I do so in Objective-C. But instead of using plain require_once function and messing around with paths and string concatenation, I would prefer something like:
importClass('myclass');
but I'm afraid that it's impossible to write a function that will include code. If I would do that in the importClass() function, I would include the class code into the implementation block of the function, which of course is nonsense. So what options do I have here?
The cleanest way to do what you want looks to be to use the Autoloader
It's not impossible at all. You can write this function:
function importClass($class) {
require_once "$class.class.php";
}
The only caveat is that any global variables declared or used inside that file will now be local to importClass(). Class definitions however will be global.
I'm not sure what this really gives you however but you can certainly do it.
In my application I have a system base class which has a similar function. The import function takes a class name, looks in a couple of related directories and finds a matching name (I also did some stuff with extensions to libraries but you may not need that) and instantiates a class inside with the same name. Then it takes that new instance and sets it as an object in the system base class.
using autoload as other answers have suggested would probably work better in your situation but this is just another way to look at it.
You can accomplish something similar using a class autoloader. I would also make sure that your include_path is set properly and that you are using a directory structure that makes sense for your classes - it's generally a good practice to NOT depend on class autoloaders, and instead include classes based on their relative path to your include_path.
I'd highly recommend browsing through Zend Framework, particularly Zend_Loader, for a good (if not over-architected) implementation. Also notice that Zend Framework will work without an autoloader in place - each file calls require_once on its direct dependencies, using their nice, organized directory structure.

Categories