CodeIgniter Forums
Using $this->request on __construct - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: Using $this->request on __construct (/showthread.php?tid=87435)



Using $this->request on __construct - Worked - 04-19-2023

Hello,

I have a question related to the use of the "getMethod()" function, and that is how to load it in the constructor. Currently the controller handles GET, POST, PUT and DELETE calls, but except for GETs, I always do the same data check on others and I wanted to write that check directly in the constructor and not in each method of the controller, but it returns the following error: "Error Call to a member function getMethod() on null".

The code is the following:
PHP Code:
public function __construct()
 {
    $this->employeesModel = new EmployeesModel();

    if (in_array($this->request->getMethod(), ['delete''post''put']) && ! $this->__validate_employee() )
    {
        $this->feedback_employee_name $this->request->getPost('Lastname') .', '$this->request->getPost('Firstname');

        return $this->__handle_validate_errors();
    }
}
// - --  ---  ------------------------------------------------------------ 

In the thread about the deprecated state of the $upper parameter and they mention the use of is() (kenjis recommends is() method), but it shows the same error.

Any idea how to use the $request inside the constructor?,
Thanks.

PS: I know, I could change "in_array(..., [...])" to "$this->request->getMethod() !== 'get' ", but they can change things and disappear allowed verbs or change something, so in_array gives me some more flexibility.


RE: Using $this->request on __construct - kenjis - 04-19-2023

See https://codeigniter4.github.io/CodeIgniter4/incoming/controllers.html#constructor


RE: Using $this->request on __construct - kenjis - 04-19-2023

If $this->request->getMethod() will return GET, your code will not work.


RE: Using $this->request on __construct - Worked - 04-20-2023

(04-19-2023, 05:39 PM)kenjis Wrote: See https://codeigniter4.github.io/CodeIgniter4/incoming/controllers.html#constructor
Thanks, reading the documentation after a few hours I got to that page and tried to apply it, but in the end it doesn't return if the __validate_employee() checks return false, and the $feedback_employee_name variable I create seems to lose scope and not It doesn't come either, unless I'm doing something very wrong.

kenjis Wrote:If $this->request->getMethod() will return GET, your code will not work.
I am aware, I am aware... those check blocks only have to be executed in those cases, in the case of GET there is nothing to check.

I try to explain what I want to do. In case of GET, the "registered" method is called, which simply shows the records found. In the case of POST/PUT, it should be checked before that what arrives to us through the form complies with the validation rules and if not, it returns to the page with the corresponding validation messages, otherwise it continues with the methods " register"/"update", in case of DELETE as I have been asked now I would no longer need to check all the data.

This is the entire controller, in case you see something that is escaping me or I don't quite understand.

Thank you very much for the help


PHP Code:
<?php

namespace App\Controllers;
use 
CodeIgniter\Controller;

use 
CodeIgniter\HTTP\RequestInterface;
use 
CodeIgniter\HTTP\ResponseInterface;
use 
Psr\Log\LoggerInterface;

use 
App\Models\EmployeesModel;

/**
 * Class Employees
 *
 * @see app/Config/Filters.php
 * @see app/Filters/GrantedMaster.php
 * @internal https://codeigniter4.github.io/CodeIgniter4/incoming/filters.html
 */
class Employees extends BaseController
{
    public 
$feedback_employee_name '';

    public function 
initController(
        
RequestInterface $request,
        
ResponseInterface $response,
        
LoggerInterface $logger
    
) {
        
parent::initController($request$response$logger);

        
$this->employeesModel = new EmployeesModel();

        if (
in_array($this->request->getMethod(), ['delete''post''put']) && $this->__validate_employee() !== true)
        {
            
$this->feedback_employee_name $this->request->getPost('Lastname') .', '$this->request->getPost('Firstname');

            return 
$this->__handle_validate_errors();
        }
    }
    
// - --  ---   ------------------------------------------------------------

    
public function register()
    {
        
helper('UUIDv4');

        
$dataset array_merge($this->__populate_employee_dataset(), [
            
'CodPublic' => generate_UUIDv4(),
            
'Password' => password_hash(trim($this->request->getPost('Password')), PASSWORD_BCRYPT, ['cost' => 10])
        ]);

        if (
$this->employeesModel->register($dataset) === false)
        {
            return 
redirect()->to('employees')
                ->
with('feedback'json_encode([[
                    
'Type' => 'warning',
                    
'Icon' => 'exclamation-triangle-fill',
                    
'Message' => lang('App.Error.employee_add', ['name' => $this->feedback_employee_name])
                ]]))
                ->
withInput();
        }

        return 
redirect()->to('employees')
            ->
with('feedback'json_encode([[
                    
'Type' => 'success',
                    
'Icon' => 'check-circle-fill',
                    
'Message' => lang('App.Success.employee_add', ['name' => $this->feedback_employee_name])
                ]]));
    }
    
// - --  ---   ------------------------------------------------------------

    
public function registered()
    {
        return 
view('employees', [
            
'feedback' => $this->session->getFlashdata('feedback'),
            
'resource' => $this->employeesModel->registered(),
            
'datasets' => [
                
'schedules' => $this->employeesModel->schedules(),
            ],
            
'datalist' => [
            ]
        ]);
    }
    
// - --  ---   ------------------------------------------------------------

    
public function remove(string $CodEmployee)
    {
        if (
$this->employeesModel->remove($CodEmployee) === false)
        {
            return 
redirect()->to('employees')
                ->
with('feedback'json_encode([[
                    
'Type' => 'warning',
                    
'Icon' => 'exclamation-triangle-fill',
                    
'Message' => lang('App.Error.employee_remove', ['name' => $this->feedback_employee_name])
                ]]));
        }

        return 
redirect()->to('employees')
            ->
with('feedback'json_encode([[
                    
'Type' => 'success',
                    
'Icon' => 'check-circle-fill',
                    
'Message' => lang('App.Success.employee_remove', ['name' => $this->feedback_employee_name])
                ]]));
    }
    
// - --  ---   ------------------------------------------------------------

    
public function update(string $CodPublic)
    {
        
$dataset $this->__populate_employee_dataset();

        if (
$this->request->getPost('Password') !== '')
        {
            
$dataset array_merge($dataset, [
                
'Password' => password_hash(trim($this->request->getPost('Password')), PASSWORD_BCRYPT, ['cost' => 10])
            ]);
        }

        if (
$this->employeesModel->sets($dataset$CodPublic) === false)
        {
            return 
redirect()->to('employees')
                ->
with('feedback'json_encode([[
                    
'Type' => 'warning',
                    
'Icon' => 'exclamation-triangle-fill',
                    
'Message' => lang('App.Error.employee_update', ['name' => $this->feedback_employee_name])
                ]]))
                ->
withInput();
        }

        return 
redirect()->to('employees')
            ->
with('feedback'json_encode([[
                    
'Type' => 'success',
                    
'Icon' => 'check-circle-fill',
                    
'Message' => lang('App.Success.employee_update', ['name' => $this->feedback_employee_name])
                ]]));
    }
    
// - --  ---   ------------------------------------------------------------



    /**  ***   ****************************************************************
     *                                                                                                 Funciones privadas */

    
private function __handle_validate_errors()
    {
        
$alerts = [ ];

        foreach (
$this->validation->getErrors() as $field => $message)
        {
            
array_push($alerts, [
                
'Type' => 'warning',
                
'Icon' => 'exclamation-triangle-fill',
                
'Message' => $message,
            ]);
        }

        return 
redirect()->to('employees')
            ->
with('feedback'json_encode($alerts))
            ->
withInput();
    }
    
// - --  ---   ------------------------------------------------------------

    
private function __populate_employee_dataset() : array
    {
        return [
            
'Firstname' => $this->request->getPost('Firstname'),
            
'Lastname' => $this->request->getPost('Lastname'),
            
'DNI' => $this->request->getPost('DNI'),
            
'Email' => $this->request->getPost('Email'),
            
'Phone' => $this->request->getPost('Phone'),
            
'Status' => $this->request->getPost('Status'),
            
'IDSchedule' => $this->request->getPost('Schedule'),
            
'Username' => $this->request->getPost('Username'),
        ];
    }
    
// - --  ---   ------------------------------------------------------------

    
private function __validate_employee() : bool
    
{
        
$this->validation->setRules([
            
'Firstname' => ['label' => lang('App.Employee.firstname'), 'rules' => 'required|string'],
            
'Lastname' => ['label' => lang('App.Employee.lastname'), 'rules' => 'required|string'],
            
'DNI' => ['label' => lang('App.Employee.nif_number'), 'rules' => 'required|alpha_numeric'],
            
'Email' => ['label' => lang('App.Employee.email_address'), 'rules' => 'permit_empty|valid_email|min_length[10]'],
            
'Phone' => ['label' => lang('App.Employee.phone_number'), 'rules' => 'permit_empty|numeric|min_length[6]'],
            
'Status' => ['label' => lang('App.Employee.status'), 'rules' => 'permit_empty|alpha|exact_length[1]'],
            
'Schedule' => ['label' => lang('App.Employee.schedule'), 'rules' => 'permit_empty|numeric'],
            
'FetchStart' => ['label' => lang('App.General.fetch_start'), 'rules' => 'permit_empty|valid_date'],
            
'FetchEnds' => ['label' => lang('App.General.fetch_ends'), 'rules' => 'permit_empty|valid_date'],
            
'Username' => ['label' => lang('App.Employee.username'), 'rules' => 'required|string'],
            
'Password' => ['label' => lang('App.Employee.password'), 'rules' => 'permit_empty|min_length[10]'],
        ]);

        return 
$this->validation->withRequest($this->request)->run();
    }
    
// - --  ---   ------------------------------------------------------------

}
/* End of file Employees.php */
/* Location ./app/Controllers/Employees.php */ 



RE: Using $this->request on __construct - kenjis - 04-20-2023

Have you used CI3?

In short, you cannot use redirect in the constructor in CI4.

PHP Code:
        return redirect()->to('employees')
            ->with('feedback', json_encode($alerts))
            ->withInput();