[CodeIgniter4] - Controller

The controller is the core of your entire application, because they determine how HTTP requests will be processed.

  • What is the controller?
  • Let's try it: Hello World!
  • method
  • You pass parameters to methods URI segments
  • Define a default controller
  • The remapping method
  • Private methods
  • The controller into a subdirectory
  • Constructor
  • It contains attributes
    • Request object
    • Response object
    • Logger objects
    • forceHTTPS
    • Helper
  • $ _POST data validation
  • That's all!

What is the controller?

In short, a controller is a class file, is capable of way and associated with a URI named.

Consider the following URI:

example.com/index.php/blog/ 

The above example, CodeIgniter would attempt to query a controller named Blog.php and load it.

When the name and the URI of the controller match the first section, it will be loaded.

Let's try it: Hello World!

Then you will see how to create a simple controller, open your text editor, create a new file Blog.php, then place the following code:

<?php
class Blog extends \CodeIgniter\Controller { public function index() { echo 'Hello World!'; } } 

Then save the file to  / application / controllers /  directory.

important

File names must begin with a capital letter, such as: 'Blog.php'.

Now similar to the following URL to access your site ::

example.com/index.php/blog

If all goes well, you will see ::

Hello World!

important

Class names must begin with a capital letter.

This is valid:

<?php
class Blog extends \CodeIgniter\Controller { } 

This is  not valid  in:

<?php
class blog extends \CodeIgniter\Controller { } 

In addition, make sure your controller inherits the parent controller class so that it can use the parent class.

method

In the embodiment, a method is named  index() . The "index" is always in the URI of  the second paragraph  is invoked is empty. Another display "Hello World" message is:

example.com/index.php/blog/index/ 

URI in the second paragraph of the controller used to determine which method call.

Let's try to add a new method to your controller:

<?php
class Blog extends \CodeIgniter\Controller { public function index() { echo 'Hello World!'; } public function comments() { echo 'Look at this!'; } } 

Now, through the following URL to invoke the method comments:

example.com/index.php/blog/comments/ 

You should see your new messages.

You pass parameters to methods URI segments

If your URI more than two segments, the extra segment to pass into your method as a parameter.

For example, suppose your URI like this:

example.com/index.php/products/shoes/sandals/123 

Your method will receive the third paragraph and fourth paragraph two parameters ( "sandals" and "123"):

<?php
class Products extends \CodeIgniter\Controller { public function shoes($sandals, $id) { echo $sandals; echo $id; } } 

important

If you use  URI routing  , parameters passed to your method will be the parameters of the route.

Define a default controller

CodeIgniter can set a default controller when a URI is not loaded segmentation parameters, such as when users direct access to your website's homepage. Open  application / config / routes.php  file, a default controller specified the following parameters:

$routes->setDefaultController('Blog'); 

Which, "Blog" is that you want to load controller class name, index.php If you do not pass any parameters to access your site, you will see your "Hello World" message.

For more information, see  ./source/general/routing.rst parts of the document.

The remapping method

As mentioned above, URI second paragraph usually determines which controller is called. CodeIgniter allows you to use  _remap() the method to override this rule:

public function _remap()
{
        // Some code here... } 

important

If your control includes a _remap () method, it will call the method no matter what URI parameters included. It allows you to define your own routing rules to override the default use the URI segments to determine which method to call this behavior.

The method being rewritten (the second segment is generally URI) will be passed as an argument to the  _remap() method:

public function _remap($method) { if ($method === 'some_method') { $this->$method(); } else { $this->default_method(); } } 

All other segments after the method name as  _remap() the method of the second argument, which is optional. This parameter can use PHP's call_user_func_array () function to simulate the default behavior of CodeIgniter.

E.g:

public function _remap($method, ...$params) { $method = 'process_'.$method; if (method_exists($this, $method)) { return $this->$method(...$params); } show_404(); } 

Private methods

Sometimes you may want certain methods can not be publicly accessible, to achieve this, simply a method declared private or protected, so this method can not be access to the URL. For example, if you have a following method:

protected function utility()
{
        // some code } 

Use the following URL to try to access it, you will find that is not accessible:

example.com/index.php/blog/utility/ 

The controller into a subdirectory

If you are building a large application, then the controller will be organized into a subdirectory could facilitate that. CodeIgniter can also achieve this.

You only need a simple in  application / controllers /  create a new directory in the directory, subdirectory and file into the controller.

annotation

When using this function, the first segment must be the URI specified directory, for example, suppose you have a controller in a position:

application/controllers/products/Shoes.php 

In order to invoke the controller, your URI should look like this:

example.com/index.php/products/shoes/show/123 

Each subdirectory contains a default controller, time will only contain the subdirectory in the URL is called. The default controller  / Routes.php application / Config  defined.

You can also use CodeIgniter's  ./source/general/routing.rst function to redirect URI.

Constructor

If you intend to use a constructor in your controller, you  must  add the following line of code on the inside ::

parent::__construct(…$params);

The reason is that your constructor will cover the constructor of the parent class, so we have to manually call it.

E.g:

<?php
class Blog extends \CodeIgniter\Controller { public function __construct(...$params) { parent::__construct(...$params); // Your own constructor code } } 

If you need to set some default value when your class is initialized, or some default processing, the constructor would be useful. Constructor does not return value, but may perform some default action.

It contains attributes

Each controller you create should inherit the  CodeIgniter\Controller class. This class provides several attributes for all controllers.

Request object

$this->request As the main attribute of the application  that can always be used by the class attribute ./source/libraries/request.rst.

Response object

$this->response As the main attribute of the application  that can always be used by the class attribute ./source/libraries/response.rst.

Logger objects

$this->logger Class instance  ./source/general/logging.rst has a class attribute can be used.

forceHTTPS

A way to force convenient method of access method by HTTPS, all controllers are available:

if (! $this->request->isSecure()) { $this->forceHTTPS(); } 

By default, the support for HTTP Strict Transport Security header modern browsers, this should force the browser to call a non-HTTPS HTTPS calls into calls a year. You can be modified by the duration (in seconds) as the first parameter.

if (! $this->request->isSecure()) { $this->forceHTTPS(31536000); // one year } 

annotation

You can use more global variables and functions  ./source/general/common_functions.rst, including the year, month, and so on.

Helper

You can define a secondary file array as a class property. Whenever the controller is loaded, these auxiliary files are automatically loaded into memory, so that they can be used anywhere in the process controller. :

class MyController extends \CodeIgniter\Controller
{
        protected $helpers = ['url', 'form']; } 

$ _POST data validation

The controller also provides an easy way to verify $ _POST data, a set of rules to verify as the first argument, if the authentication fails, can choose to display a set of custom error message. You can  request $ this->  This usage get POST data. Validation Library docs is available formats and details of the rules and rules of the message array.

public function updateUser(int $userID) { if (! $this->validate([ 'email' => "required|is_unique[users.email,id,{$userID}]", 'name' => 'required|alpha_numeric_spaces' ])) { return view('users/update', [ 'errors' => $this->errors ]); } // do something here if successful... } 

If you think the rules stored in the configuration file easier, you can by  Config\Validation.php defined array instead of $ rules

public function updateUser(int $userID) { if (! $this->validate('userRules')) { return view('users/update', [ 'errors' => $this->errors ]); } // do something here if successful... } 

annotation

Verification may be processed automatically in the model. You can handle at any place, you will find in some cases controller is simpler than the model, and vice versa.

That's all!

OK, in general, this is all about the controller.

Guess you like

Origin www.cnblogs.com/landv/p/12396982.html