Abey
Abey

Reputation: 23

CakePHP 3: Accessing trait from controller

How can I access a method from trait in a controller in CakePHP 3? Or is doing this against the Cake design paradigm?

I have tried the following

<?php
namespace App\Controller;
use App\Controller\AppController;
use App\Traits;
class UsersController extends AppController{
  use Traits\CommonTrait;
  public function index()
  {
    $this->Common->traitMethod();
  }
}

But I am getting

Call to a member function... on boolean

Upvotes: 2

Views: 1626

Answers (2)

Rayann Nayran
Rayann Nayran

Reputation: 1135

I made a change in your code.

See how use Traits and its methods:

<?php
namespace App\Controller;

use App\Controller\AppController;
use App\Traits\CommonTrait;

class UsersController extends AppController{

  use CommonTrait;

  public function index()
  {
    $this->traitMethod();
  }
}

Upvotes: 1

Chin Leung
Chin Leung

Reputation: 14921

When you use a trait, your class will have access to the functions of the trait.

$this->traitMethod();

Upvotes: 1

Related Questions