Контроллеры
Контроллер - это сердце твоего приложения, так как он определяет каким образом будет обработан HTTP запрос.
- Что Такое Контроллер?
- Hello World
- Функции
- Передача URI Сегментов в Твои Функции
- Назначение Контроллера по Умолчанию
- Перегрузка Вызовов Функций
- Контроль Выводимых Данных
- Внутренние Функции
- Организация Контроллеров во Подкаталогах
- Конструктор Класса
- Зарезервированные Имена Функций
Что такое Контроллер?
Контроллер(Controller) - это файл содержащий класс, названный таким образом, что он может быть ассоциирован с URI.
Рассмотрите следующий URI:
www.your-site.com/index.php/blog/
В примере описанном выше, Code Igniter попытается найти контроллер blog.php и загрузить его.
Когда имя контроллера совпадает с первым сегментом URI, происходит его загрузка.
Попробуй: Hello World!
Давай создадим простой контроллер, чтобы ты понял как он действует. Используя свой любимый редактор создай файл с именем blog.php, и вставь в него следующий код:
Теперь сохрани его в свой каталогapplication/controllers/.
Теперь зайди на свой сайт, используя подобный адрес:
www.your-site.com/index.php/blog/
Если все было сделано правильно ты должен увидеть Hello World!.
Примечание: Имя класса должно начинаться с буквы в верхнем регистре. Ниже пример правильного названия:
<?php
class Blog extends Controller {
}
?>
А это не правильно:
<?php
class blog extends Controller {
}
?>
Также убедись, что твой контроллер - потомок класса - Controller(контроллер-родитель), тогда он сможет унаследовать все родительские функции.
Функции
В описанном выше примере, у контроллера есть функция index(). Функция с именем "index" всегда загружается по умолчанию, если второй сегмент URI отсутствует. Сообщение "Hello World" можно было вызвать так:
www.your-site.com/index.php/blog/index/
Второй сегмент адреса определяет, какая функция должна быть вызвана.
Добавь в свой контроллер новую функцию:
Теперь загрузи следующий URL чтобы вызвать функцию comments :
www.your-site.com/index.php/blog/comments/
Ты должен увидеть свое новое сообщение.
Передача URI Сегментов в Твои Функции
Если твой URI содержит больше двух сегментов, то они будут переданы в твою функцию как параметры.
Например если твой URI выглядит как этот:
www.your-site.com/index.php/products/shoes/sandals/123
В твою функцию будут переданы сегменты 3 и 4("sandals" и "123"):
<?php
class Products extends Controller {
function shoes($sandals, $id)
{
echo $sandals;
echo $id;
}
}
?>
Важно: Если ты используешь URI Маршрутизацию, сегменты переданные в твою функцию будут переадресованы.
Назначение Контроллера по Умолчанию
В случае когда URI отсутствует(запрашивается корневой URL твоего сайта) Code Igniter загружает контроллер назначенный по умолчанию. Для того, чтобы определить этот контроллер отрой application/config/routes.php файл и установи эту переменную:
$route['default_controller'] = 'Blog';
Здесь Blog это имя контроллера, который ты хочешь использовать. Теперь при загрузке твоего index.php без указанию URI сегментов ты увидишь Hello World сообщение.
Перегрузка Вызовов Функций
As noted above, the second segment of the URI typically determines which function in the controller gets called. Code Igniter permits you to override this behavior through the use of the _remap() function:
function _remap()
{
// Some code here...
}
Important: If your controller contains a function named _remap(), it will always get called regardless of what your URI contains. It overrides the normal behavior in which the URI determines which function is called, allowing you to define your own function routing rules.
The overridden function call (typically the second segment of the URI) will be passed as a parameter the _remap() function:
function _remap($method)
{
if ($method == 'some_method')
{
$this->$method();
}
else
{
$this->default_method();
}
}
Processing Output
Code Igniter has an output class that takes care of sending your final rendered data to the web browser automatically. More information on this can be found in the Views and Output class pages. In some cases, however, you might want to post-process the finalized data in some way and send it to the browser yourself. Code Igniter permits you to add a function named _output() to your controller that will receive the finalized output data.
Important: If your controller contains a function named _output(), it will always be called by the output class instead of echoing the finalized data directly. The first parameter of the function will contain the finalized output.
Here is an example:
function _output($output)
{
echo $output;
}
Please note that your _output() function will receive the data in its finalized state. Benchmark and memory usage data will be rendered, cache files written (if you have caching enabled), and headers will be sent (if you use that feature) before it is handed off to the _output() function. If you are using this feature the page execution timer and memory usage stats might not be perfectly accurate since they will not take into acccount any further processing you do. For an alternate way to control output before any of the final processing is done, please see the available methods in the Output Class.
Private Functions
In some cases you may want certain functions hidden from public access. To make a function private, simply add an underscore as the name prefix and it will not be served via a URL request. For example, if you were to have a function like this:
function _utility()
{
// some code
}
Trying to access it via the URL, like this, will not work:
www.your-site.com/index.php/blog/_utility/
Organizing Your Controllers into Sub-folders
If you are building a large application you might find it convenient to organize your controllers into sub-folders. Code Igniter permits you to do this.
Simply create folders within your application/controllers directory and place your controller classes within them.
Note: When using this feature the first segment of your URI must specify the folder. For example, lets say you have a controller located here:
application/controllers/products/shoes.php
To call the above controller your URI will look something like this:
www.your-site.com/index.php/products/shoes/123
Each of your sub-folders may contain a default controller which will be called if the URL contains only the sub-folder. Simply name your default controller as specified in your application/config/routes.php file
Code Igniter also permits you to remap your URIs using its URI Routing feature.
Class Constructors
If you intend to use a constructor in any of your Controllers, you MUST place the following line of code in it:
parent::Controller();
The reason this line is necessary is because your local constructor will be overriding the one in the parent controller class so we need to manually call it.
If you are not familiar with constructors, in PHP 4, a constructor is simply a function that has the exact same name as the class:
<?php
class Blog extends Controller {
function Blog()
{
parent::Controller();
}
}
?>
In PHP 5, constructors use the following syntax:
<?php
class Blog extends Controller {
function __construct()
{
parent::Controller();
}
}
?>
Constructors are useful if you need to set some default values, or run a default process when your class is instantiated. Constructors can't return a value, but they can do some default work.
Reserved Function Names
Since your controller classes will extend the main application controller you must be careful not to name your functions identically to the ones used by that class, otherwise your local functions will override them. The following is a list of reserved names. Do not name your controller functions any of these:
- Controller
- CI_Base
- _ci_initialize
- _ci_scaffolding
If you are running PHP 4 there are some additional reserved names. These ONLY apply if you are running PHP 4.
- CI_Loader
- config
- database
- file
- helper
- helpers
- language
- library
- model
- plugin
- plugins
- scaffolding
- script
- view
- vars
- _ci_assign_to_models
- _ci_autoloader
- _ci_init_class
- _ci_init_scaffolding
- _ci_is_instance
- _ci_load
- _ci_load_class
- _ci_object_to_array
That's it!
That, in a nutshell, is all there is to know about controllers.