# Controllers

## Manually Create&#x20;

Follow these steps to create a new controller in PHPFast:

1. Go to the `application/Controllers` director&#x79;**.**
2. Create a new PHP file and name it according to your controller, e.g., `HomeController.php`.
3. Define the controller class by extending `System\Core\BaseController` to inherit core framework functionality.

Here is a basic example:

```php
<?php
namespace App\Controllers;

use System\Core\BaseController;

class HomeController extends BaseController
{
    public function index()
    {
        // Fetch and display a home page
        echo "Welcome to PHPFast";
    }
}
```

## Using the Command-Line Interface

This command generates a new controller file in the `application/Controllers` directory.

* It creates a basic controller template, helping you set up new features faster.

**Command:**

```sh
php init Controllers <controller_name>

// Example: php init controllers Users
```

This creates `UsersController.php` inside `application/Controllers`

## Controller Structure

### Basic Controller

```php
<?php
namespace App\Controllers;

use System\Core\BaseController;

class UsersController extends BaseController
{
    public function index()
    {
        // URL: /users
        // Router: $routes->get('users', 'UsersCotroller::index');
        echo "Welcome to the Users Page!";
    }

    public function show($id)
    {
        // URL: /users/123
        // Router: $routes->get('users/(:num)', 'UsersCotroller::show/$1');
        echo "User ID: " . $id;
    }
}
```

### Advanced options

When you define the **UsersController** inside the `Controllers/backend/` folder and use the `UsersModel`

The structure looks like:

```php
/app
 ├── /Controllers
 │    ├── /backend                    // Add a backend folder
 │    │    ├── UsersController.php
 │
 ├── /Models
 │    ├── UsersModel.php
 │
 ├── /Views
 │    ├── users_list.php
```

And **UsersController**:

```php
<?php
namespace App\Controllers\Backend;  // Define the correct namespace

use App\Controllers\BaseController;

class UsersController extends BaseController
{
    public function index()
    {
        // URL: /users
        // Router: $routes->get('users', 'UsersCotroller::index');
        echo "Welcome to the Users Page!";
    }

    public function show($id)
    {
        // URL: /users/123
        // Router: $routes->get('users/(:num)', 'UsersCotroller::show/$1');
        echo "User ID: " . $id;
    }
}
```

## **Routing to a Controller**

To route a URL to a specific controller method, use:

### Basic

```php
$routes->get('users', 'UsersController::index')
```

* URL: **`/users`**
* Calls: **`index()`** method in **`UsersController`**

### **Dynamic Parameters**

```php
$routes->get('users(:num)', 'UsersController::show:$1');
```

* URL: **`/users/123`**
* Calls: **`show(123)`** method in **`UsersController`**

## Models in Controller

Controllers can interact with Models to handle database operations.&#x20;

Below is an example of how to load a model and use it within a controller:

```php
<?php
namespace App\Controllers;

use System\Core\BaseController;
use App\Models\UsersModel;

class UsersController extends BaseController
{
    protected $usersModel;

    public function __construct()
    {
        // Load the model inside the constructor
        $this->usersModel = new UsersModel();
    }

    public function index()
    {
        // Fetch all users from the model
        $users = $this->usersModel->getUsers();
        
        $this->data('users ', $users);
        
        // Pass the users to a view for rendering
        return $this->render('frontend', 'user/index);
    }
}
```

## Render Views & Assets Data to Views

```php
<?php
namespace App\Controllers;

use System\Core\BaseController;
use App\Models\UsersModel;

class UsersController extends BaseController {
    public function index(){
        // Set the page title
        $this->data('title', 'Welcome to PHPFast');
        
        // Render the home page within the 'themes' layout
        echo $this->render('themes', 'home/home');
    }
}
```

## Load CSS and JS File

```php
<?php
namespace App\Controllers;

use System\Core\BaseController;
use System\Libraries\Assets;

class UsersController extends BaseController {
    public function __construct(){
        $this->assets = new Assets();

        // Manual way
        $this->assets->add('css', 'css/style.css', 'head');
        $this->assets->add('js', 'js/main.js', 'footer');

        $this->data('assets_header', $this->assets->header('backend'));
        $this->data('assets_footer', $this->assets->footer('backend'));

        // Using Block
        Render::asset('css', 'css/style.css', ['area' => 'frontend', 'location' => 'head']);
        Render::asset('js', 'js/main.js', ['area' => 'frontend', 'location' => 'footer']);
        
        // Note: Make sure CSS and JS files are contained in Views/Frontend/Assts
    }
    
    public function index(){
        return $this->render('frontend', 'home/index',);
    }
}
```

## Get data from Controller

### Manual way

```php
<!DOCTYPE html>
<html>
<head>
    <?= !empty($assets_header) ? $assets_header : ''; ?>
</head>
<body>
    <?= !empty($assets_footer) ? $assets_footer : ''; ?>
</body>

</html>

```

### Using Block

In `Blocks/Head/Views/default.php`

<pre class="language-php"><code class="lang-php">&#x3C;head>
<strong>    &#x3C;?= \System\Libraries\Render::renderAsset('head', 'frontend') ?>
</strong><strong>&#x3C;/head>
</strong></code></pre>

In `Blocks/Footer/Views/default.php`

<pre class="language-php"><code class="lang-php">&#x3C;head>
<strong>    &#x3C;?= \System\Libraries\Render::renderAsset('footer', 'frontend') ?>
</strong><strong>&#x3C;/head>
</strong></code></pre>

## Message Handle

```php
<?php
namespace App\Controllers;

use System\Core\BaseController;

class UsersController extends BaseController {
    public function search($input){
        if(empty($input)) {
            return $this->error('An error occurred', [], 404);
        }
    }
}
```

Output:

```
{"status":"error","message":"An error occurred","errors":[]}
```

## Caching in Controller

```php
<?php
namespace App\Controllers;

use System\Drivers\Cache\UriCache;
use System\Core\BaseController;

class UsersController extends BaseController {
    protected $cache;

    public function __construct(){
        // Get level cache
        $cache_gzip = option('cache_gzip') ?? 0; 
        
        // Init cache
        $this->cache = new UriCache($cache_gzip, 'html');
    }
    
    public function index(){
        // Get cache
        $cacheData = $this->cache->get();
        
        // Check empty cache
        if(empty($cacheData)){
            Render::asset('css', 'style.css', ['area' => 'frontend', 'location' => 'head']);
            Render::asset('js', 'jfast.1.1.4.js', ['area' => 'frontend', 'location' => 'footer']);
        
            $result = Render::html('frontend', $this->data);
            
            $cacheData = $this->cache->set($result, true);
        }
        
        $this->cache->render($cachData);
    }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.cmsfullform.com/documents/controllers.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
