cakephp override construct in child controller - oop

I'm wondering if it is possible to inherit/override constructors in child controllers in cakephp.
In my AppController.php
I have it like this:
public function __construct( $request = null, $response = null ) {
parent::__construct( $request, $response );
$this->email = new CakeEmail();
$this->_constants = array();
$this->_constants['some_var'] = $this->Model->find( 'list', array(
'fields' => array( 'Model.name', 'Model.id' )
) );
}
and in my child controller SomeController.php, it inherits the parent constructor
public function __construct( $request = null, $response = null ) {
parent::__construct( $request, $response );
}
and when I tried to access $this->email and $this->_constants['some_var'] they both are null. But as soon as I put the code directly in SomeController.php instead of inheriting, it worked.
Did I do something wrong or this is simply not approachable for cake?
Also I tried the same with function beforeFilter(), same thing happened.
But it makes sense that each controller to have its own beforeFilter().

I wouldn't even try overriding the _construct' function of the appController. That's what thebeforeFilter,beforeRender` methods are for. It looks like you are just trying to pass vars to each controller from the appController. You can do that like so...
class AppController extends Controller {
var $_constants = array();
public function beforeFilter(){
$this->_constants[] = array('this', 'that', 'the other');
}
}
and in your model's controller you can access the variable like so...
class UsersController extends AppController {
public function add(){
pr($this->_constants);
}
}
It's a different story if you are trying to send the variables to the view (slightly). Just use the set method
class AppController extends Controller {
public function beforeFilter(){
$this->set('_constants', array('this', 'that', 'the other'));
}
}
and in any view you can just call the _constants variable with pr($_constants);. Because it is in the appController it should be available on every view.

Related

notification system in Laravel 8

I am working on a laravel app where i have a user(organizer) who post an event ,and other users can comment on this event .
I am trying to make notifications system in laravel 8 between the organizer and the users when commenting on these event !
but i get this error (Call to a member function notify() on null).
This is my class :
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
class NewCommentPosted extends Notification
{
use Queueable;
protected $user;
protected $event;
public function __construct($user, $event)
{
$this->user = $user;
$this->event = $event;
}
public function via($notifiable)
{
return ['database'];
}
public function toArray($notifiable)
{
return [
'user' => $this->user->name,
'eventTitle' => $this->event->title,
'eventId' => $this->event->id
];
}
This is storefunction() in my controller :
namespace App\Http\Controllers;
use App\Models\Event;
use App\Models\Comment;
use App\Notifications\NewCommentPosted;
use Illuminate\Http\Request;
class CommentController extends Controller
{
public function store(Event $event)
{
request()->validate([
'content' => 'required|min:5'
]);
$comment = new Comment();
$comment->content = request('content');
$comment->user_id = auth()->user()->id;
$event->comments()->save($comment);
$event->user->notify(new NewCommentPosted(auth()->user(), $event));
return redirect()->route('events.show', [$event->id, $event->title]);
}
Any help please !!?

Set & Get session variable value

I am setting session variable in function of a controller like below.
use Illuminate\Support\Facades\Session;
class UserController extends Controller
{
public function store(Request $request)
{
session(['user_name' => $user_name]);
}
}
I am trying to access that session variable in another function of another controller.
use Illuminate\Support\Facades\Session;
class DashboardController extends Controller
{
public function __construct()
{
dd(session('user_name')); // I am not getting value here
}
}
I am not getting value from Session Variable.
You can do it like this
use Illuminate\Support\Facades\Session;
class UserController extends Controller
{
public function store(Request $request)
{
session()->put('user_name', $user_name);
}
}
And you can get it another controller or anywhere like this
session()->get('user_name');
Hope this will help you, thanks..

Laravel Read User id in Controller constructor

In my controller(s), instead of fetchingAuth::id() in each method, I've set up an $id property in the controller's class and fetched it once in the constructor. then, in the rest of the methods i'm just refering $this->id, is it considered safe or am I doing something wrong?
Code Sample: http://pastebin.com/pvju54eh
What you could do is inject the Guard instance in your controller and then assign the currently logged in user (if there is one) to a class property:
<?php namespace App\Http\Controllers;
use Illuminate\Contracts\Auth\Guard;
class SomeController extends Controller
{
protected $auth;
protected $user;
public function __construct(Guard $auth)
{
$this->auth = $auth;
$this->user = $this->auth->user();
}
public function someMethod()
{
// Get logged in user’s ID
$userId = $this->user->id;
}
}
I do not see any major problems with this approach even though I have not seen approach used often.
Myself I find it easier to get the $request->user() in controller from Request though.

Cakephp overide Controller constructer

I would to override constroller constrcuter's like this :
class XControler extends AppController {
public $attr = null;
public __construct(){
$this->attr = new YController();
}
}
But when I do that I take error ! can you explain me why and how I do that with out using requestAction just OOP !
thanks
Controllers are responsible for dealing with end user requests. Each controller action should have a view, and normally you would not want to access the methods from YController inside XController.
What you want to achieve can be done this way:
XController.php
App::uses('YController', 'Controller');
class XController extends AppController {
public $attr;
public $uses = array('Person');
public function __construct($request = null, $response = null) {
$this->attr = new YController();
parent::__construct($request, $response);
}
public function method1() {
// you can now call methods from YController:
$this->attr->Ymethod1();
}
}
YController.php
class YController extends AppController {
public function Ymethod1() {
// ....
}
}
However, the business logic should be inside Models or Components. This is the proper way to share methods between more controllers.
So your XController should look like:
class XController extends AppController {
public $uses = array('Model1');
public function action1() {
$this->Model1->method1();
// ....
}
}

creation of model object in controller yii

can any one tell me how to create a model object inside a constructor in yii. I had written the code as belo
<?php
class DistributorsController extends Controller
{
public $layout = '//layouts/column4';
public $defaultAction = null;
public function __construct()
{
echo '<br>Into constructor';
parent::__construct('Distributors','distributors');
}
public function actionDistributors()
{
$this->render("ChannelMask");
}
}
?>
But it is displaying only "Into constructor" string and view is not showing in my browser.
You need to call a model into the Controller.
Create a model, then in Controller, call it like :
Distributor::model()->findAll($criteria); //many models
or
Distributor::model()->findById($id); // one model
Like any other place if you want to create a new model:
$model = new Distributors();
or
$model = $this->loadModel($id, 'Distributors');
if you want to populate your model with existing data, then:
$model = Distributor::model()->findAll(); // all there is
or
$model = Distributor::model()->findByPk($id); // find by primary key