Skip to content

Controllers

Controllers are the core of your application because they determine how to handle HTTP requests.

What is a Controller

A controller is simply a class file that handles HTTP requests. URI routing associates a URI with a controller and executes a method within the controller.

Each controller you create should extend the Controller class. This class provides several useful features for all your controllers.

Naming Conventions for Controllers

Controller names should match the class names and use lowercase letters uniformly. When the resource name consists of multiple words, use underscores to connect them.

Constructors

The constructor of a controller is optional.

If you need to perform some initialization work in the controller, you can create a __construct() constructor, but don't forget to add parent::__construct() in the method.

php
<?php

use framework\libraries\Controller;

class test extends Controller
{
    function __construct()
    {
        parent::__construct();
        // Add your code here
    }
}

WARNING

We recommend that you do not use constructors in controllers. Instead, use thebefore()method of middleware to validate requests.

Included Methods

WeeSpeed includes some properties that can be used in controllers.

Request Object

WeeSpeed encapsulates the methods of the request instance 的方法, You can use $this to access the following methods of the request object:

get($name, $default = null)

Get query parameters, i.e., retrieve parameters from $_GET .

  Parameters:$name:Parameter name
       $default:Default value

Return value: The submitted parameter value or the default value. Returns null if no value is submitted and no default value is provided.

post($name, $default = null)

Get POST parameters, i.e., retrieve parameters from $_POST .

  Parameters:$name:Parameter name
       $default:Default value

Return value: The submitted parameter value or the default value. Returns null if no value is submitted and no default value is provided.

file($name)

Get uploaded files, i.e., retrieve parameters from $_FILE .

  Parameters:$name:Parameter name

Return value: The uploaded file object. Returns null if no file is submitted.

header($name, $default = null)

Get parameters submitted in the header.

  Parameters:$name:Parameter name
       $default:Default value

Return value: The submitted parameter value or the default value. Returns null if no value is submitted and no default value is provided.

server($name, $default = null)

Get server parameters, i.e., retrieve parameters from $_SERVER .

  Parameters:$name:Parameter name
       $default:Default value

Return value: The submitted parameter value or the default value. Returns null if no value is submitted and no default value is provided.

rawBody()

Get the raw POST request body. This is useful when retrieving POST request data in a non-application/x-www-form-urlencoded format.

Return value: The request body.

data($name, $value)

Add data to the request object for passing parameters for the same request among controllers, middleware, or other methods.

  Parameters:$name:Parameter name
       $value:Default value

Return value: No return value.

data($name)

Read data with the specified name from the request object.

  Parameters:$name:Parameter name

Return value: The variable value. Returns null if no value exists.

Response Object

WeeSpeed encapsulates the methods of the response class., You can use $this to access the following methods of the response object:

success($data)

Output a JSON-formatted successful response. The response structure is as follows:

Field NameTypeDescriptionExample
codeintStatus code0
msgstringStatus descriptionok
dataanyResponse data

error($code, $msg='',$data = null)

Output a JSON-formatted error response. The response structure is as follows:

Field NameTypeDescriptionExample
codeintStatus code400001
msgstringStatus descriptionNo access permission
dataanyResponse dataData for front - end debugging

redirect($url)

Redirect to the specified URL.

rawOutput($httpCode, $data = null)

Directly output an HTTP response. The parameters are as follows:

Field NameTypeDescriptionExample
httpCodeintHTTP status code200
dataanyResponse data

TIP

success(), error(), redirect() and rawOutput()methods do not terminate the program. You need to use return to terminate the program when you don't want to execute subsequent code. For example:

php
if ($res == 0) {
    return $this->success($res);
} else {
    return $this->error($code, $msg);
}

Helper Methods

getRealIp()

Get the client's real IP address.

Return value: A string representing the IP address.

isAjax()

Determine whether the request is an Ajax request.

Return value: true or false.

Example

If we want to create an /admin/users , interface, we can create a controller/admin.php file with the following content:

php
<?php
use framework\libraries\Controller;
class admin extends Controller
{
    //Get the user list
    //GET: /admin/users?page=1
    function users_get()
    {
        $page = $this->get('page', 1);
        $where = [
            'is_delete'=>0
        ];
        $users = Db::select(
            'user',
            "*",
            $where,
            [],
            [
                'limit' => [$page,10]
            ]
        );
        return $this->success( $users);
    }

    //Get user details
    //GET: /admin/users/{id}
    function users_get($id)
    {
        $user = Db::get('user', "*",['id' => $id]);
        //:TODO Check if the user exists
        return $this->success($user);
    }

    //Create a user
    //POST: /admin/users
    function users_post()
    {
        // Get request parameters
        $name = $this->post('name');
        // Omit other parameters and validation logic
        $id=Db::insert('user',$data);
        return $this->success($id);
    }

    // Update user information
    //POST: /admin/users/{id}
    function users_post($id)
    {
        // Get request parameters
        $name = $this->post('name');
        // Omit other parameters and validation logic
        $res=Db::table('user',$data,['id'=>$id]);
        return $this->success($res->rowCount());
    }

    // Delete a user
    //DELETE: /admin/users/{id}
    function users_delete($id)
    {
        // Omit validation logic
        $res=Db::delete('user',['id'=>$id]);
        return $this->success($res->rowCount());
    }

}