<?php
class PI_Controller_Plugin_AssetGrabber extends Zend_Controller_Plugin_Abstract
{
public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
{
/*
The module name
*/
$moduleName = $request->getModuleName();
/*
This modules requires the user to be loggedin in order to see the web pages!
*/
$loginRequiredModules = array('admin');
if (in_array($moduleName,$loginRequiredModules)) {
$adminLogin = new Zend_Session_Namespace('adminLogin');
if (!isset($adminLogin->loggedin)) {
/*--------------------------------------
Here I want to redirect the user
*/
$this->_redirect('/something');
}
}
}
}
I'm trying to do a redirect $this->_redirect('/something') but doesn't work! Do you know how can I do a redirect in this case?
Best Regards,
... rest of code
if (!isset($adminLogin->loggedin)) {
$baseUrl = new Zend_View_Helper_BaseUrl();
$this->getResponse()->setRedirect($baseUrl->baseUrl().'/something');
}
... rest of code
<?php
class AlternativeController extends Zend_Controller_Action
{
/**
* Redirector - defined for code completion
*
* #var Zend_Controller_Action_Helper_Redirector
*/
protected $_redirector = null;
public function init()
{
$this->_redirector = $this->_helper->getHelper('Redirector');
}
public function myAction()
{
/* Some Awesome Code */
$this->redirector('targetAction', 'targetController');
return; //Never reached!
}
}
You need to get the redirector helper, then you can define the targetAction and targetController with the redirector. That should do it.
Either use Zend_Controller_Action_HelperBroker to get the redirect helper or do the redirect directly from the Request object.
See the examples given in
Redirect in Front Controller plugin Zend
Related
In this Symfony route
/**
* #Route("/board/{board}/card/{card}", name="card_show", methods={"GET"}, options={})
*/
public function show(Board $board, Card $card): Response
{
$card->getLane()->getBoard(); // Board instance
// ...
}
How is it possible to add the {board} parameter programatically, since it is already available in {card}? Now, I always need to add two parameters, when generating links to show action.
After some research I've found the RoutingAutoBundle (https://symfony.com/doc/master/cmf/bundles/routing_auto/introduction.html#usage) which would provide the functions I need, but it's not available for Symfony 5 anymore.
Thanks.
Okay, after some investigation I've found this question
Which lead me to this helpful answer.
My controller action (with #Route annotation) looks like this:
/**
* #Route("/board/{board}/card/{card}", name="card_show", methods={"GET"})
*/
public function show(Card $card): Response
{
}
We just have one argument ($card) in method signature, but two arguments in route.
This is how to call the route in twig:
path("card_show", {card: card.id})
No board parameter required, thanks to a custom router.
This is how the custom router looks like:
<?php // src/Routing/CustomCardRouter.php
namespace App\Routing;
use App\Repository\CardRepository;
use Symfony\Component\Routing\RouterInterface;
class CustomCardRouter implements RouterInterface
{
private $router;
private $cardRepository;
public function __construct(RouterInterface $router, CardRepository $cardRepository)
{
$this->router = $router;
$this->cardRepository = $cardRepository;
}
public function generate($name, $parameters = [], $referenceType = self::ABSOLUTE_PATH)
{
if ($name === 'card_show') {
$card = $this->cardRepository->findOneBy(['id' => $parameters['card']]);
if ($card) {
$parameters['board'] = $card->getLane()->getBoard()->getId();
}
}
return $this->router->generate($name, $parameters, $referenceType);
}
public function setContext(\Symfony\Component\Routing\RequestContext $context)
{
$this->router->setContext($context);
}
public function getContext()
{
return $this->router->getContext();
}
public function getRouteCollection()
{
return $this->router->getRouteCollection();
}
public function match($pathinfo)
{
return $this->router->match($pathinfo);
}
}
Now, the missing parameter board is provided programatically, by injecting and using the card repository. To enable the custom router, you need to register it in your services.yaml:
App\Routing\CustomCardRouter:
decorates: 'router'
arguments: ['#App\Routing\CustomCardRouter.inner']
I am using code igniter and my URL structure looks like this:
http://localhost:8888/project/register
Register in this case is the controller.
I am trying to pass an ID to this URL, something like so:
http://localhost:8888/project/register/1234 so that I can use this value in my controller.
I am running into an issue trying to figure that out since the position of this ID is meant for the name of a method within the controller.
Is it possible to add a value in this position without it thinking its a method or do I need to do something like :
http://localhost:8888/project/register?code=1234 ?
Trying to access it like so: $registerPin = $this->common->nohtml($this->uri->segment(2));
Update:
As a hack workaround, I did this.. Any better ways?
URL: http://localhost:8888/project/register/c/1234
/**
* Pass our signup code for demo purposes
*/
public function c(){
// Did we come here from a Sign-up Pin?
$registerPin = $this->common->nohtml($this->uri->segment(3));
if($registerPin){
$this->session->set_userdata(array(
'registerPin' => $registerPin
));
}
// Redirect to register
redirect(site_url("register"));
}
public function index()
{
echo $this->session->userdata('registerPin');
}
One solution would be to use the Controller's _remap functionality, although I've not used this the way you're intending to use it. (Hopefully it works)
See: https://www.codeigniter.com/userguide3/general/controllers.html#remapping-method-calls
<?php
class Register extends MY_Controller{
public function __construct()
{
parent::__construct();
}
// -----------------------------------------------------------------------
/**
* Controller remapping
*/
public function _remap( $method, $params = [] )
{
if( is_numeric( $method ) )
{
$this->index( $method );
}
else
{
$this->$method();
}
}
// -----------------------------------------------------------------------
/**
* Index method
*/
public function index( $num )
{
# code...
}
// -----------------------------------------------------------------------
}
Another solution would be to use URI routing.
See: https://www.codeigniter.com/userguide3/general/routing.html
$route['register/(:num)'] = 'register/index/$1';
Neither of these examples may be fully functional in your case, but should be close to what you need.
I want to stop the controller action when a block code is complete.
This some example code.
class Controller extends \Phalcon\Mvc\Controller {
/**
* Check if user have access
*
*/
protected function isAllowed($perm = false)
{
/**
* Always allowed if $perm not defined
*/
if (!$perm) {
return false;
}
/**
* if user not login
*/
if (!$this->authentication->isLoggedin()) {
/* Redir to login */
$this->response->redirect( $this->url->get('authentication/login') );
return false;
} else {
/* Check for user access */
if ($this->authorization->isAllowed($perm)) {
return true;
} else {
/* if not have access, it will be redir to index */
$this->flash->warning("U not have permission to access page");
return $this->response->redirect( $this->url->get('administrator/') );
}
}
}
}
and the another controller that extend from base is
class postController extends Controller {
/**
* Add group
*
*/
public function addAction()
{
/*
Check user access
this must redirect to login and stop exe script
*/
$this->isAllowed('group_add');
/*
But when i check with `Postman`
without auth i redirect to login.
but when i use post method and fill the header body like bellow.
i still redir to login but this code execute. why? and how to stop it.
*/
/* If request is POST */
if ($this->request->isPost()) {
/* Get all inputs from form */
$inputs = $this->request->getPost();
$name = $this->request->getPost('name', ['trim', 'striptags', 'string']);
$definition = $this->request->getPost('definition', ['trim', 'striptags', 'string']);
/* Filter validation */
if (!Validation::make($inputs, $this->rules())) {
$this->flash->error('...');
... redirect to page
return false;
}
/* Get from database */
$model = new AauthGroups;
$group = $model->findFirst([
'name = :name:',
'bind' => [
'name' => $name
]
]);
/* If cant find group then add it */
if (!$group) {
/* Set & save data */
$model->name = $name;
$model->definition = $definition;
$model->save();
$this->flash->success('Yay!! We found that name in database, do u want to change it?');
return;
}
/* If it finded than set flash error */
else {
$this->flash->error('Oops!! We found that name in database, do u want to change it?');
return;
}
}
}
}
I tried to use exit; but the view will not render. Can you explain it?
Can you try send()-ing the response like this?
/* Redir to login */
$this->response->redirect( $this->url->get('authentication/login') )->send();
return false;
If this does not work, you may have to use beforeExecuteRoute in your "BaseController".
class Controller extends \Phalcon\Mvc\Controller {
public function beforeExecuteRoute()
{
// Check if logged
if (!$notLogged) {
$this->response->redirect('....')->send();
return false;
}
}
I will be able to check those later. Hope it works for you by then.
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Fatal error: Call to undefined method CookieComponent::del()
I am creating a plugin that uses a login method from my SiteUsers controller, but I am getting the error message:
Call to undefined method SiteUsersController::_doLogIn()
Plugin Site Users Controller:
class SiteUsersController extends AppController {
public $name = 'SiteUsers';
/**
* login_competition
*
*/
public function login_challenge() {
$this->autoRender = false;
if (!$this->_doLogIn($this->request->data['SiteUser'])) {
$this->Session->setFlash('ERROR');
}
}
$this->redirect('/');
}
}
Site User Controller in main App
class SiteUsersController extends AppController {
public $name = 'SiteUsers';
/**
* _doLogIn()
*
* #param unknown_type $data
* #return string|string
*/
protected function _doLogIn($data) {
$this->_user = $this->SiteUser->getUserByEmailPassword(Sanitize::clean($data));
if (!empty($this->_user)) {
$this->Session->Write('SiteUser.id', $this->_user['SiteUser']['id']);
$this->Session->Write('SiteUser.first_name', $this->_user['SiteUser']['first_name']);
$this->Session->Write('SiteUser.username', $this->_user['SiteUser']['username']);
return true;
}
return false;
}
}
I would suggest you to move your _doLogIn into component. That way you don't have to make it public and users won't get to it directly through browser and it will be available to all controllers.
Current _doLogIn could be rewritten to use new components method so sitewide there is no big deal if it is used widely.
Just in case ;) http://book.cakephp.org/2.0/en/controllers/components.html
Zend framework talk.I'm initializing in my bootstrap class My_Action_Helper_Custom (extending Zend_Controller_Action_Helper_Abstract) to make it available to all of my controllers.
Could I just disable it for a specific action where I dont need it?
thanks
Luca
Are you referring to disabling the preDispatch() or postDispatch() hooks for a particular controller action?
If so, I'd add some form of blacklist property to the helper, for example
/**
* #var array
*/
private $blacklistActions = array();
public function addBlacklistAction($action)
{
// store actions in string form
// eg, module.controller.action
$this->blacklistActions[] = $action;
}
public function preDispatch()
{
$request = $this->getRequest();
$action = sprintf('%s.%s.%s',
$request->getModuleName(),
$request->getControllerName(),
$request->getActionName());
if (in_array($action, $this->blacklistActions)) {
return;
}
// the rest
}