CodeIgniter is a simple and
powerful open source web application framework for PHP. Today, we'll do
some core "hacks" to this framework to change and improve its
functionality. In the process, you'll gain a better understanding of the
intricacies of CodeIgniter.
Disclaimer
- It is not recommended to apply these hacks to an existing project. Since they change some of CodeIgniter's core functionality, it can break the existing code.
- As of this writing, CodeIgniter 1.7.2 is the latest stable release. These hacks are not guaranteed to work for future (or past) releases.
- Even though CodeIgniter is designed to be PHP 4 compatible, some of these hacks are not. So you will need a server with PHP 5 installed.
- When you make any changes to the files inside the system folder, you should document it somewhere for future reference. Next time you upgrade CodeIgniter (even though they do not release updates very often), you may need to reapply those changes.
1. Autoloading Models PHP 5 Style
The Goal
On the left side, you see the regular way of loading a model in CodeIgniter, from within a Controller. After this hack, we will be able to create objects directly. The code is cleaner, and your IDE will be able to recognize the object types. This enables IDE features such as auto-complete, or previewing documentation.
There are two more side effects of this hack. First, you are no longer required to extend the Model class:
And you no longer have to add a require_once call before you do model class inheritance.
The Hack
All we need to do is add a PHP 5 style autoloader function.Add this code to the bottom of system/application/config/config.php:
<?php
// ...
function
__autoload(
$class
) {
if
(
file_exists
(APPPATH.
"models/"
.
strtolower
(
$class
).EXT)) {
include_once
(APPPATH.
"models/"
.
strtolower
(
$class
).EXT);
}
}
?>
If you are interested in applying this hack for controllers too, you can use this code instead:
<?php
// ...
function
__autoload(
$class
) {
if
(
file_exists
(APPPATH.
"models/"
.
strtolower
(
$class
).EXT)) {
include_once
(APPPATH.
"models/"
.
strtolower
(
$class
).EXT);
}
else
if
(
file_exists
(APPPATH.
"controllers/"
.
strtolower
(
$class
).EXT)) {
include_once
(APPPATH.
"controllers/"
.
strtolower
(
$class
).EXT);
}
}
?>
Any time you try to use a class that is not defined, this __autoload
function is called first. It takes care of loading the class file.
oleh : Mohd Khairol
Sumber Rujukan : https://code.tutsplus.com/tutorials/6-codeigniter-hacks-for-the-masters--net-8308
0 comments:
Post a Comment