Extends cakephp plugin - cakephp

I'm using spark_plug plugin on cakephp, this plugin provides an authentication-acl system for register and admin users in cakephp. I want to add some new code and functionalities to the user's controller but I don't want to change the "main" plugin files.
I was thinking if it is possible leave the "main" plugin controller as it (unchanged) "\app\plugins\spark_plug\controllers\users_controller.php" and create a secondary controller with all the new code and functionalities, something like this "\app\controllers\users_controller.php" and extends the plugin "main" controller.
Is that possible? and how achieve that?
Or do you think is there any other way to do what I want?
Thanks!

You could perhaps use composition rather than inheritance? I.e. create a "app\controllers\users_controller" that has inside it an instance of the plugin's controller. The UsersController passes through any unmodified actions via stubs, eg:
class UsersController extends AppController {
...
var spark_plug_users_controller;
...
public function __construct() {
parent::__construct();
App::import('Controller', 'SparkPlug/Users'); // this is probably wrong.
$this->spark_plug_users_controller = new UsersController; // as is this.
$this->spark_plug_users_controller->constructClasses();
}
...
//example non-overridden method
function login() {
return $this->spark_plug_users_controller->login();
}
...
}
your problem would be accessing protected/private methods within the spark_plug Users controller. But if you did not need to, this may work.

Related

calling plugin's controller from AppController in CakePHP 3

I have written a plugin for CakePHP 3.4.*.
This plugin will check for Database configuration has been set or not, if not then It you move user through a GUI interface to setup database configuration just like wordpress.
The plugin is working perfectly, but it has to be loaded manually by visiting url of the plugin
http://example.com/installer/install
where installer is the plugin name which is calling InstallController class inside plugins/Installer/src/Controller/ directory
Now what I want to check it automatically and redirect user to the Installation interface if database connection couldn't be established.
For that I have written a function inside InstallController of plugin's controller
public function installationCheck() {
$db = ConnectionManager::get('default');
if(!$db->connect()) {
if(Configure::read('Database.installed') == true) {
$this->Flash->error(__("Database connection couldn't be established. Please, re-configure it to start the application"));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__("Please configure your database settings for working of your application"));
return $this->redirect(['action' => 'index']);
}
}
return true;
}
Now the Question.
What is the easiest way to call this method from /app/src/Controller/AppController.php file of the main application?
Simple answer, you don't!
Shared controller logic belongs either in AppController itself, a Component or a Trait. The AppController should never being accessing methods defined in other controllers, these shouldn't be made accessible to it.
For what you're doing you probably want to do this in a component that you can load via your AppController or the relevant controller.
So your component would look something like:-
<?php
namespace Installer\Controller\Component;
use Cake\Controller\Component;
class InstallComponent extends Component
{
public function installationCheck()
{
// Method's logic
}
}
Which you would then load in the relevant controller:-
public function initialize()
{
parent::initialize();
$this->loadComponent('Installer.Install');
}
Then you can use the component's method from the controller like:-
$this->Install->installationCheck();
You should not Do that!
If you need to access another controller I recommend you to move that functionality to a Component, that are packages of logic that are shared between controllers.

Cakephp 3 - CRUD plugin - Use id from auth component

Currently, I'm using the CRUD v4 plugin for Cakephp 3. For the edit function in my user controller it is important that only a user itself can alter his or her credentials. I want to make this possible by inserting the user id from the authentication component. The following controller method:
public function edit($id = null){
$this->Crud->on('beforeSave', function(\Cake\Event\Event $event) {
$event->subject()->entity->id = $this->Auth->user('id');
});
return $this->Crud->execute();
}
How can I make sure I don't need to give the id through the url? The standard implementation requires the url give like this: http://domain.com/api/users/edit/1.json through PUT request. What I want to do is that a user can just fill in http://domain.com/api/users/edit.json and send a JSON body with it.
I already tried several things under which:
$id = null when the parameter is given, like in the example above. Without giving any id in the url this will throw a 404 error which is caused by the _notFound method in the FindMethodTrait.php
Use beforeFind instead of beforeSave. This doesn't work either since this isn't the appropriate method for the edit function.
Give just a random id which doesn't exist in the database. This will through a 404 error. I think this is the most significant sign (combined with point 1) that there is something wrong. Since I try to overwrite this value, the CRUD plugin doesn't allow me to do that in a way that my inserting value is just totally ignored (overwriting the $event->subject()->entity->id).
Try to access the method with PUT through http://domain.com/api/users.json. This will try to route the action to the index method.
Just a few checks: the controllerTrait is used in my AppController and the crud edit function is not disabled.
Does anyone know what I'm doing wrong here? Is this a bug?
I personally would use the controller authorize in the Auth component to prevent anyone from updating someone else's information. That way you do not have to change up the crud code. Something like this...
Add this line to config of the Auth component (which is probably in your AppController):
'authorize' => ['Controller']
Then, inside the app controller create a function called isAuthorized:
public function isAuthorized($user) {
return true;
}
Then, inside your UsersController you can override the isAuthorized function:
public function isAuthorized($user) {
// The owner of an article can edit and delete it
if (in_array($this->request->action, ['edit'])) {
$userId = (int)$this->request->params['pass'][0];
if ($user['id'] !== $userId) {
return false;
}
}
return parent::isAuthorized($user);
}

CakePHP 3.x: how to extend the Request class

I have a plugin and I wish to extend the Request class (Cake\Network\Request), to add new methods and properties that can be used by the controllers of my plugin.
How to do?
Thanks.
Create your extended request class and simply pass an instance of it to the dispatcher in your apps webroot/index.php front controller:
https://github.com/cakephp/app/blob/3.0.0/webroot/index.php#L35
// ....
use App\Network\MyCustomRequest;
$dispatcher = DispatcherFactory::create();
$dispatcher->dispatch(
MyCustomRequest::createFromGlobals(), // there it goes
new Response()
);

CakePHP : override BasicAuthenticate.php

I'm trying to override lib/Cake/Controller/Component/Auth/BasicAuthenticate.php,
because I need to change the unauthenticated() method.
So I copied and modified the file to app/Lib/Cake/Controller/Component/Auth/BasicAuthenticate.php (also tried without the 'Cake' folder), but the changes are not taken into account.
My edit works when modifying directly the core file but I'd rather not.
How should I do ?
I'm using Cake 2.5
Check if you really need to override a core class
To me this looks like you are on the wrong track, overriding the class shouldn't be neccesary unless for example you have no controler over where and how the basic authentication adapter is being used (for example in a plugin that doesn't offer configuration).
If you'd really need to overwrite the class, then the path should be
app/Lib/Controller/Component/Auth/BasicAuthenticate.php
and it should work just fine (it does for me, using CakePHP 2.5.6).
http://book.cakephp.org/2.0/en/core-utility-libraries/app.html#overriding-classes-in-cakephp
Use a custom authentication handler instead
If you have control over the adapter configuration, the I'd suggest that you extend the BasicAuthenticate class instead, and only override the unauthenticate() method, and finally make the auth component use the custom adapter.
Something like
app/Controller/Component/Auth/CustomBasicAuthenticate.php
App::uses('BasicAuthenticate', 'Controller/Component/Auth');
class CustomBasicAuthenticate extends BasicAuthenticate {
public function unauthenticated(CakeRequest $request, CakeResponse $response) {
// do something special
}
}
Controller
public $components = array(
'Auth' => array(
'authenticate' => array(
'CustomBasic'
)
)
);
See also the Creating Custom Authentication objects section in the Cookbook.

CakePHP default layout, can't pass values to default.ctp

I have one page website, on homepage(Layout/default.ctp) I have 2 forms, subscribe and contact form that are being controlled over contact controller. With $this->set('some_val', 'test'); I can set value from AppController, but not from contact controller, how can I set values from contact controller to be available in default.ctp except with sessions?
public function beforeFilter() {
parent::beforeFilter();
//pr('beforeFilter'); // i was testing is this happening or not
//exit();
$tester = 'test';
$this->set(compact('tester'));
}
and in default.ctp I just pr($this->viewVars); to make sure that I have tester value, but it is always empty.
Is this right approach how to implement several controllers in one page design?
Another question is there a place/function where I could check is current request post or not, I would like to check for each request what is it?
Thank you.
Not sure if I understand correctly, but it sounds like you might need multiple layouts:
class CarsController extends AppController
{
public function index($page)
{
/* Your logic */
if ( $page == 'other' ) {
$this->render('view', 'layout');
} else {
$this->render('view-other', 'layout-other');
}
}
}
For more information i'd suggest looking at: http://api20.cakephp.org/class/controller#method-Controllerrender
try an echo $tester; in your default, it should be available.
If the request is post, you would have data in $this->data.

Resources