I have made my custom controller and set it as default in my main config file.
All the other actions are working fine. But when there is any error i have made :
public function actionError() {
echo 'Error'; die;
}
and then i made a not found request. It did not did the action written by me, but did default action.
Please suggest!!
If you want to use your custom error action, you have to configure the errorAction in the errorHandler application component. You can do so in your main.php. If your controller is CustomController you'd configure:
'components' => array(
// ...
'errorHandler' => array(
'errorAction' => 'custom/error',
),
// ...
You dont have to echo inside the controller.Create a view file inside your views folder and render it like so public function actionError(){ $this->render('viewName') }
Related
We have web pages, where user will be redirected to $this->goHome(), if the session timeouts or user logouts. We have to destroy the all the session so, we have to add a function with destroying session. This function should be executed before running any action/controller in Yii2 i.e. similar to hooks in codeigniter. We have tried a helper function with destroying session and we have called the function as HomeHelper::getHelpDocUrlForCurrentPage(); in main.php layout, but the layout will be executed after running action in controller, it should work on running any controller as we have 100+ controllers. How this can be achieved, please suggest us in right way. Thanks in advance.
in
config/main.php
you could try using 'on beforeAction'
return [
'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
'bootstrap' => [
'log',
....
],
'on beforeAction' => function($event){
// your code ..
} ,
'modules' => [
....
],
...
];
While #ScaisEdge solution would work I believe application config is not proper place to hold application logic.
You should use filters to achieve result you want.
First you need to implement filter with your logic. For example like this:
namespace app\components\filters;
class MyFilter extends yii\base\ActionFilter
{
public function beforeAction() {
// ... your logic ...
// beforeAction method should return bool value.
// If returned value is false the action is not run
return true;
}
}
Then you want to attach this filter as any other behavior to any controller you want to apply this filter on. Or you can attach the filter to application if you want to apply it for each action/controller. You can do that in application config:
return [
'as myFilter1' => \app\components\filters\MyFilter::class,
// ... other configurations ...
];
You might also take a look at existing core filters if some of them can help you.
I'm working on a PHP project which has many pages calling a POST request, such as login, register, commenting and etc.
I've tried processing all POST requests in a single file named post.php, with each request containing 'formtype' parameter, like so,
$formtype = $_POST['formtype'];
if ($formtype == "register") {
register_function_here();
} else if ($formtype == 'login') {
login_function_here();
} else {
die("Error: No FORMTYPE");
}
and I've also tried having separate files for separate functions, such as login.php, register.php, comment.php and etc.
Which method is better for processing POST requests?
Are there any disadvantages for processing all POST requests in a single file, as I've done?
Thanks in advance!
I guess you mean you do not want to:
GET index.php
POST user/register.php
POST user/login.php
index.php
user/
register.php
login.php
404.php
What #ArtisticPhoenix about the MVC (model, view, controller) is actually what you tried. Well, for the Controller part i mean.
You try to create router.
You could do that. If you are new to coding and you got time i even would say: do it.
If you dont have time and need a solution then i suggest searching a framework - at least for routing.
To get started:
First i found was this: https://www.taniarascia.com/the-simplest-php-router/
If you want to go further then you SHOULD start using OOP.
A class is then a controller, a method an action.
(some got like every action is a class like zend expressive framework).
Example:
Create a routing config
// file: config/routes.php
return [
'routes' => [
[
'path' => "/login",
'class' => LoginController::class,
'method' => 'loginAction',
'allowed_methods' => ['POST'],
],
[
'path' => "/logout",
'class' => LoginController::class,
'method' => 'logoutAction',
'allowed_methods' => ['GET', 'POST'],
],
// ...
],
];
Create Controllers
// file: Controller/LoginController.php
namespace Controller;
class LoginController
{
public function loginAction()
{
// ...
}
public function logoutAction()
{
// ...
}
}
Now use the requested path and route it to the controller.
If no route found then return a HTTP 404 "Not Found" response .
// file: index.php
// load routing config
$routes = require 'config/routes.php';
// ...
// ... this now is up to you.
// you should search in the config if the requested path exists
// and if the request is in the allowed_methods
// and then create a new controller and call the method.
I strongly recommend Object Oriented Programming, using classes, one source file per class.
I have a CakePHP 3.3.14 application where I've created 2 subdirectories, webroot/data/downloads/ and webroot/data/master
I want to put these paths in a custom configuration file and reference them in a Controller. But I can't see how to do this.
I've followed the documentation on Configuration but it's not very clear.
So what I've done:
Created config/my_config.php
The above file defines an array:
return [ 'downloadsPath' => 'webroot/data/downloads/', 'masterPath' => 'webroot/data/master/' ];
In config/bootstrap.php I've put: Configure::load('my_config', 'default');
How do I then use this in a Controller? If I put Configure::read('my_config.masterPath'); it gives an error saying: Class 'App\Controller\Configure' not found
If I add use Cake\Core\Configure; to the top of my Controller, that clears the error but the return value is null:
debug(Configure::read('my_config.masterPath')); // null
Loading another config file just extends the default App.config. So just use \Cake\Core\Configure::read('masterPath') and you are good.
EDIT
If it is your goal to have different config paths you could do it like this:
// my_config.php
return [
'MyConfig' => [
'masterPath' => '...',
...
]
];
Then use the config like this:
<?= \Cake\Core\Configure::read('MyConfig.masterPath') ?>
In Yii's config.php we have this statement which declares which Controller is the default and only-one Error-Handler within the application:
'errorHandler' => array(
'errorAction' => 'site/error',
),
So, I need to have an actionError() under my SiteController, to get the errors previewed in my site, but this is not what I really need.
I am trying to change the Yii::app()->errorHandler->errorAction on the fly, throughout my custom-controllers who extend the base CController (Yii's base controller).
Till now, I have tried something like this:
<?php
class AdminController extends CController {
public $layout = '//layouts/admin';
public function init() {
parent::init();
Yii::app()->errorHandler->errorAction = '/admin/error';
}
}
But gives no results, nor hope. Note that I also have this URL configuration:
'/admin' => '/admin/home',
'/admin/<controller:\w+>' => '/admin/<controller>',
'/admin/<controller:\w+>/<action:\w+>/<id:\d+>' => '/admin/<controller>/<action>',
'/admin/<controller:\w+>/<action:\w+>' => '/admin/<controller>/<action>',
And this means I have a whole Controllers-Views group named admin, and they are stored in following directories:
protected/controllers/admin
protected/views/admin
So by that logic, I have ErrorController in both: admin and controllers root, and by the same structure in the views directory.
That's what I have tried, and I really appreciate help, so thank you all in advance!
You should try this :
Yii::app()->setComponents(array(
'errorHandler'=>array(
'errorAction'=>'/admin/error'
)
));
http://www.yiiframework.com/doc/api/1.1/CModule#setComponents-detail
I am using zend framework 2.1. I am trying to load the output of my indexAction from my login controller inside of my index controller. The end result I am trying accomplish is to just have my login form loaded on the index page as if it is part of that view.
I have searched for a few hours with no avail. I have attempted to use $this->view->action, which i've seen in earlier versions of zf2 but that has not worked either.
Any information would be helpful.
Taken from this blog, which explains in depth why $this->view->action() has been removed from ZF2, an example how to use the forward() (ZF2 documentation) controller plugin:
You can forward all necessary data to another controller inside your index controller action using the forward() controller plugin like this:
public function indexAction() {
$view = new ViewModel();
$login_param = $this->params('login_param');
$login = $this->forward()->dispatch('App\Controller\LoginController', array(
'action' => 'display',
'login_param' => $login_param
));
$view->addChild($login, 'login');
return $view;
}
In your view, all you need to do is:
<?php echo $this->login; ?>
Please note that the forward() plugin might return a Zend\Http\PhpEnvironment\Response instead. This happens if you use a redirect() in your login controller / action.
Also, if the Servicemanager claims to not find App\Controller\LoginController, have a look in your module.config.php. Look for a section called controllers.
Example:
[...]
'controllers' => array(
'invokables' => array(
'LoginCon' => 'App\Controller\LoginController',
'IndexCon' => 'App\Controller\IndexController',
'DataCon' => 'App\Controller\DataController',
)
),
[...]
Here, there is an alias for your login controller called LoginCon, you should use this name as controller name in the dispatch() method instead.