Controllers



Controllers are classes designed with Object Oriented Programming (OOP), which are used to interact with the model and call the relevant view depending on the user requests. URL requests from users are made to the corresponding methods of these classes. These URL requests execute the method belonging to a class. Since the structures that users first interact with are controllers, we begin the narration in this section.

Folder: Projects/Any/Controllers/
Note: The URL examples used in the explanation are given assuming that you are working on localhost.

 

 

# Section Headings


# Running Simple Code

Controller Section
Method Section
Parameters Section
Dependency Injection [5.7.7]
Control of Ajax Requests [6.0.0]

# Default Opening Controller
# Startup Controllers

Excluding
Including
Multiple Startup Controllers Usage
Data Sending to Controllers

# Controller Restoration

Configuration
Restore Constant

 

 

# Running Simple Code


Below is a sample code that returns the "Welcome to World of ZN" message. Create a Blog.php file with the same name in the directory whose path is specified below and edit the content as follows.

File: Projects/Frontend/Controllers/Blog.php
<?php namespace Project\Controllers;

class Blog extends Controller
{
    public function main()
    {
        echo "Welcome to World of ZN";
    }
}

Below is the URL that must be entered in the address bar to run this code.

Run: localhost/blog/main veya localhost/blog
Welcome to World of ZN
Controller Section

ZN's current default controller is Home.php. And there is a main method in this controller. It is not necessary to use the main phrase in the address bar in the requests made over the URL. To run the main method in Home.php, it is sufficient to write localhost/home in the address bar.

File: Projects/Frontend/Controllers/Blog.php
<?php namespace Project\Controllers;

class Blog extends Controller
{
    public function main()
    {
        echo 'Home Page';
    }
}
Run: localhost/blog
Method Section

The file name of the controller to be accessed in the first section is written in the address bar, and the method name of that controller to be run is written in the second section. If the method name is main, it does not need to be specified in the URL.

File: Projects/Frontend/Controllers/Blog.php
<?php namespace Project\Controllers;

class Blog extends Controller
{
    public function main()
    {
        echo 'Welcome to World of ZN';
    }

    public function comments()
    {
        echo 'Run Now!';
    }
}

To run the above comments method, we edit our URL address as follows.

Run: localhost/blog/comments

To run the Main method, simply type the controller name in the URL address.

Run: localhost/blog
Parameters Section

The third and later parts of the URL address are used to send parameters to the methods via the URL. If the parameter is sent to the main method, the second and following sections are used as parameters. The parametric values sent over the URL hold the parameters of the related method. The example below shows how to use the incoming parameters.

File: Projects/Frontend/Controllers/Products.php
<?php namespace Project\Controllers;

use Output;

class Products extends Controller
{
    public function main($price, $value)
    {
        Output::write('{0} - {1}', [$price, $value]);
    }

    public function computer($price, $value)
    {
        Output::write('{0} - {1}', [$price, $value]);
    }
}
Run: localhost/products/computer/price/1000
price - 1000

If you are going to make a request to the Main method, you do not need to use the method name.

Run: localhost/products/price/5000
price - 5000
Dependency Injection [5.7.7]

The ZN Framework allows object injections to controller methods as of the specified version. So you can call any library as parameter in methods.

File: Projects/Frontend/Controllers/Products.php
<?php namespace Project\Controllers;

class Products extends Controller
{
    protected $database;

    public function __construct(\DB $db)
    {
        $this->database = $db;
    }

    public function main(\Post $post, \Get $get)
    {
        $post::name('Example');
    }
}
Warning: This usage ignores standard URI parameter sending. For this reason, it is recommended to use the URI:: library to use parametric values.

At the same time as automatic injection, parameter-specified libraries can also be used inside views associated with specified variable names.

File: Projects/Frontend/Views/Products/main.wizard.php
{{ $post::name() }}
Example
Control of Ajax Requests [6.0.0]

Ajax control can be added by setting the return type value of the controller method to void. Thus, requests made to this method other than ajax are terminated with exit and are not processed.

File: Projects/Frontend/Controllers/Home.php
<?php namespace Project\Controllers;

use Http;

class Home extends Controller
{
    public function ajaxControlProcess() : void
    {
        # your codes...
    }
}

 

 

# Default Opening Controller


The default opening controller in the ZN code framework is the Home.php file. You do not need to specify the opening controller in the URL. Therefore, when localhost/ is typed in the URL address, this controller works directly. To change this, simply open the Config/Routing.php file and change the openController setting below.

File: Projects/Frontend/Config/Routing.php
'openController' => 'home'

 

 

# Startup Controllers


You may want to run code that will be valid for the entire system before all controllers. You can use one of your existing controllers to write the code that will work in the entire system. Controllers to be run at startup are specified from the configuration file below.

File: Config/Starting.php
Startup Controllers
mixed $constructors = 'Initialize'
It is used to indicate the current and first running controllers on all controllers. By default, the Initialize:: controller is defined. Looking inside the Controllers/ directory you can see that the Initizalize.php controller exists
mixed $destructors Used to specify the current and then running controllers on all controllers.

If you are going to run more than one controller or a function connected to the same controller, you must specify the value as a string.

'constructors' => ['StartingController1:functionName', 'StartingController2:functionName']

An example usage is given below.

File: Controllers/Initialize.php
<?php namespace Project\Controllers;

use User;

class Initialize extends Controller
{
    public function main()
    {
        if( CURRENT_CFPATH !== 'user/login' && ! User::isLogin() )
        {
            redirect('user/login');
        }
    }
}
Not: Fonksiyon adı main() ise yapılandırmada belirtmeye gerek yoktur.
Excluding [5.2.0]

In some cases, you may want the startup controller not to work on some controllers. For example, when a login is done, the login controller may enter redirection due to the login control in the startup controller. You have to exclude some controllers for such situations. The exclude constant is used for this. When specifying the controllers to be excluded in this array, the filename of the controller must be used.

File: Controllers/Initialize.php
<?php namespace Project\Controllers;

use User;

class Initialize extends Controller
{
    const exclude = ['Login']; # The filename of the controller must be specified.

    public function main()
    {
        if( ! User::isLogin() )
        {
            redirect('Login');
        }
    }
}

URI information as well as the controller can be excluded. In this case, the data to be written in the exclude array should be written in lowercase letters.

File: Controllers/Initialize.php
<?php namespace Project\Controllers;

use User;

class Initialize extends Controller
{
    const exclude = ['account/login']; # It should be written in lower case.

    public function main()
    {
        if( ! User::isLogin() )
        {
            redirect('account/login');
        }
    }
}
Including [5.2.0]

It is the opposite of excluding pages. It specifies on which controllers the initial controller will be valid when using this constant. If desired, both exclude and include constants can be used together.

File: Controllers/Initialize.php
<?php namespace Project\Controllers;

use User;

class Initialize extends Controller
{
    const include = ['home', 'product', 'contact'];

    public function main()
    {
        
    }
}
Multiple Startup Controllers Usage

The use of multiple initial controllers is needed in cases where some codes should be valid for all controllers and some should not be valid for certain controllers.

First of all, which controllers will be used as initial controllers must be specified in the configuration file.

File: Config/Starting.php
'constructors' => ['Initialize', 'Master'],

After the above configuration, both Initialize and Master controllers will now be used as initial controllers.

File: Controllers/Master.php
<?php namespace Project\Controllers;

class Master extends Controller
{
    const exclude = ['Login'];

    public function main()
    {
        # The head and body pages to be used by the masterpage are specified.
        Masterpage::headPage('head')->bodyPage('body');
    }
}

Above, while using Masterpage:: is disabled for the Login controller.

File: Controllers/Initialize.php
<?php namespace Project\Controllers;

use Config;

class Initialize extends Controller
{
    public function main()
    {
        # Config/Database.php -> database
        Config::database('database', 
        [
            'database' => 'test',
            'user'     => 'root',
            'password' => '123456'
        ]);
    }
}

The database configuration above will be enabled for both Login and all other controllers.

As can be seen, the use of more than one startup controller is necessary in cases where such configurations need to be parsed.

Data Sending to Controllers [5.3.9]

With the View class, which is used to send data to the view, if desired, it can send data to the currently working controller. There are 2 methods for this.

Defining const extract = true in the controller.
Config/Starting.php -> extractViewData = true definition.

File: Controllers/Initialize.php
<?php namespace Project\Controllers;

class Initialize extends Controller
{
    public function main()
    {
        View::sendData('Send Data')->otherData('Other Data');
    }
}

If one of the 2 methods specified after sending the sample data above is used, these values can be accessed with the $this object in the controller.

File: Controllers/MyController.php
<?php namespace Project\Controllers;

class MyController extends Controller
{
    const extract = true;

    public function main()
    {
        echo $this->sendData;
        echo $this->otherData;
    }
}
Send Data
Other Data

If the submissions will be valid for all controllers, it would be wiser to activate it from the Config/Starting.php value instead of the const extract definition in each controller.

Direct Access [5.6.0]

With this update, you can get data directly as below without using const extract.

<?php namespace Project\Controllers;

class MyController extends Controller
{
    public function main()
    {
        echo View::sendData();
        echo View::otherData();
    }
}
Send Data
Other Data

 

 

# Controller Restoration [4.3.0]


While editing the code on some controllers in your live project, you may not want users to be affected by the results of these edits and you can be directed to a different page.

this can be done in 2 ways;

* With configuration file.
With const restore constant in controller.

Configuration

Restoration settings are made through the following configuration file. The settings in this configuration file are given below.

File: Config/Project.php
Restoration
string $mode = '' this setting must be set to 'restoration' to initiate restoration processes.
mixed $machinesIP = []
The IP information of these computers is used to determine on which computers the restoration will be valid. If more than one IP information is to be entered, it can be specified in the array type.
mixed $pages = [] The pages to be repaired are specified. If it is a single page, you can assign a string. If more than one page is to be specified, the pages that have been repaired are specified in the series, respectively. If all pages are repaired, string "all" assignment is used. What should not be forgotten here is that if there is an error on the page and users encounter this error, this setting should be made. Otherwise it is not very wise to set the page to be redirected to the running page. When the restored page is visited, the path of that page is specified to which page the users are asked to be directed to.
string $routePage When a request is made to any of the pages specified in the Restoration Pages setting, it will be directed to the page where this setting is specified. It is not the page name that should be written in this section, but the controller/function information.
Restore Const

It is not necessary to change the $mode value in this use.

machinesIP Which IP/IPS addresses will work. If more than one thread is to be specified, the array is used.
functions Which functions to work on. array for more than one function or all for all.
routePage The page to which the visitors will be directed is specified.
<?php namespace Project\Controllers;

class Home extends Controller
{
    const restore =

    [
        'machinesIP' => '127.0.0.2',   // Array or String
        'functions'  => 'main',        // Array or String
        'routePage'  => 'home/restore' // Route Controller/Function
    ];

    public function main(string $params = NULL)
    {

    }

    public function restore()
    {
        echo 'System Restore!';
    }
}