How to read and write session in helper--Cakephp - php

I have to use the session in cakephp helper.
To read the session is possible in helper but write session is not.
I don't know how to do it.
Can anyone tell me?
Basic problem is that:
I have created one custom helper which call several times in view for single request.
Suppose helper has called for 5 times.
In helper for textarea some random id has going to be assign.
I need to collect those ids in some variable and then use it for the js function.
If you have new idea related to this problem then please share.
I have added the "session helper" in my custom helper.
Thanks!!!

You can extend SessionHelper , for that place a create a ExtendSessionHelper.php in View/Helper
and add following code in it.
App::uses('SessionHelper', 'View/Helper');
class ExtendSessionHelper extends SessionHelper {
public function write($name, $value = null) {
return CakeSession::write($name, $value);
}
}
Use following code in helpers array of controller to use this helper
var $helpers = array( 'Session' => array('className' => 'ExtendSession'));

Related

How to make the controller data override view controller in Laravel?

To build a sidebar that has a lot of dynamic data on it I learned about View composers in Laravel. The problem was that View Composers trigger when the view loads, overriding any data from the controller for variables with the same name. According to the Laravel 5.4 documentation though, I achieve what I want with view creators :
View creators are very similar to view composers; however, they are
executed immediately after the view is instantiated instead of waiting
until the view is about to render. To register a view creator, use the
creator method:
From what I understand, this means if I load variables with the same name in the controller and the creator, controller should override it. However this isn't happening with my code. The view composer:
public function boot()
{
view()->creator('*', function ($view) {
$userCompanies = auth()->user()->company()->get();
$currentCompany = auth()->user()->getCurrentCompany();
$view->with(compact('userCompanies', 'currentCompany'));
});
}
And here is one of the controllers, for example:
public function name()
{
$currentCompany = (object) ['name' => 'creating', 'id' => '0', 'account_balance' => 'N/A'];
return view('companies.name', compact('currentCompany'));
}
the $currentCompany variable in question, for example, always retains the value from the creator rather than being overridden by the one from the controller. Any idea what is wrong here?
After some research, I realized my initial assumption that the data from the view creator can be overwritten by the data from the controller was wrong. The creator still loads after the controller somehow. But I found a simple solution.
For those who want to use View composers/creators for default data that can get overwritten, do an array merge between the controller and composer/creator data at the end of the boot() method of the composer/creator, like so:
$with = array_merge(compact('userCompanies', 'currentCompany', 'currentUser'), $view->getData());
$view->with($with);

Auth not working in view

I'm trying to make certain buttons appear only to certain user types, I was adding this code around buttons in my view:
<li><?php
if($this->Auth->user('role_id')==8){
echo $this->Html->link(__('New Consumer Product'), array('action' => 'add'));
}
?>
</li>
But that just gave me the error Error: AuthHelper could not be found. so I added the following in my AppController:
public $helpers = array('Auth');
However this just gave me the following error:
Helper class AuthHelper could not be found.
Error: An Internal Error Has Occurred.
What's happening here? Shouldn't it have worked when I added the Auth helper into my AppController?
I'd previously been using Auth in my UsersController with no problems at all.
You can't use Auth in the view. That's only for controllers.
There are actually a few options such as setting/passing a variable for it, but this is the correct way as per the manual
if((AuthComponent::user('role_id') == 8) {
...
}
In your AppControllers beforeRender() or beforeFilter() just set the active user to the view:
public function beforeRender() {
$this->set('userData', $this->Auth->user());
}
And work with that variable in the view. I prefer to not use the static method calls on the component inside a view, it's the wrong place for a component and also static calls aren't something you want to introduce a lot because of tight coupling.
My BzUtils plugin comes with a helper that can deal with this variable or can be configured to read the user data from session and offers some convenience methods.
in cake 3.x I found the only thing that worked is to set the variable in AppController.php as so:
public function beforeRender(\Cake\Event\Event $event) {
$this->set(['userData'=> $this->Auth->user(),
]);
}
the key difference being you have to pass in $event...
Auth is a component not a helper. There is no Auth helper.
You can read the Authenticated user from the following command
$user = $this->Session->read("Auth.User");

Yii passing value from one controller to another

I am using Yii framework for my application. My application contain 4 controllers in which I want to pass value from one controller to another.
Let us consider site and admin controller. In site controller, I manage the login validation and retrieves admin id from database. But I want to send admin id to admin controller.
I try session variable, its scope only within that controller.
Please suggest the possible solution for me.
Thanks in advance
You want to use a redirect:
In the siteController file
public function actionLogin()
{
//Perform your operation
//The next line will redirect the user to
//the AdminController in the action called loggedAction
$this->redirect(array('admin/logged', array(
'id' => $admin->id,
'param2' => $value2
)));
}
in the adminController file
public function loggedAction($id, $param2)
{
//you are in the other action and params are set
}

CakePHP Sessions design

I am very new to CakePHP and the whole MVC framework. My question is where is the best place to incorporate sessions in my website.
I want to start a session as soon as a user visits the site and check if it is valid and if the user is logged in (via a session attribute) before each call to a controller.
Should I be placing the logic to check for a valid session in the AppController? if so how can I do that because nothing instantiates the AppController so I cannot use $this->html->session().
Many Thanks
You are on the right track, but take another look at the documentation on Sessions.
You want to be using $this->Session->read/write/check/etc
Cakephp will always start a session if you've included the Session component and for the most part this is exactly what you want. In the AppController you only need to tell CakePHP to use the Session component.
Something like this...
public $components = array(
'Session',
'RequestHandler',
'Cookie'
);
And then include the helper as well...
public $helpers = array('Html', 'Form', 'Session');
Now you're ready to rock.
To store a value in the session :
$this->Session->write("myvalue");
to read a value from the session:
$this->Session->read("myvalue");
You can also check if a value is set using :
$this->Session->check("myvalue");
You can also use beforeFilters in your controller to block access to the controller:
public function beforeFilter(){
parent::beforeFilter();
if(!$this->Session->check("id")){
$this->redirect("/users/login");
}
}
Alternatively just wrap the above in a private method and call the method on the first line of all the actions you want to control access to.

Zend: Get the current url for use in Controller

I have this controller which will simply change the language in a session so I can set it in the bootstrap.
Except I want to change '$this->_redirect ( 'library/recipes/list' );' to be the URL of the page they are on. Ive tried a few functions and they dont seem to work.
Im a newbie Zend user, thanks!
class Library_LanguageswitchController extends Zend_Controller_Action {
public function init() {
$this->_helper->layout->disableLayout ();
$this->_helper->viewRenderer->setNoRender ();
}
public function switchAction() {
$session = new Zend_Session_Namespace ( 'whatcould' );
$session->language = $this->_getParam ( 'lang' );
$this->_redirect ( 'library/recipes/list' );
}
}
There is no built-in way to do this afaik. You want to redirect back to the referer, which may or may not be stored in $_SERVER['HTTP_REFERER'].
The best approach I can think of is writing a Zend_Controller_Action_Helper with a method signature like this
// Returns the referer from $_SERVER array or $fallback if referer is empty
public function getReferer($fallback);
// proxy to getReferer()
public function direct($fallback);
Then you could use
public function switchLanguageAction
{
// ... insert code to switch the language for this user ...
$this->_redirect( $this->_helper->referer('/fallback/to/url') );
}
As an alternative, you could use a custom redirect helper that can achieve the same in one go.
http://framework.zend.com/manual/en/zend.controller.actionhelpers.html#zend.controller.actionhelper.redirector.basicusage mentions $this->_redirector->redirectAndExit();
I think that maybe you are looking at this from the wrong angle. A controller is fired after the routing has completed. From what I am seeing you really want to change the language and then route to the controller. This would be achieved via customizing the front controller and tapping in to one of the events there.
Another simple way to grab/set the referer is via adding a param to your frontController in your Bootstrap code:
$frontController = Zend_Controller_Front::getInstance();
$frontController->setParam('referer', $_SERVER['HTTP_REFERER']);
and then grab the referer from your controller like so:
$referer = $this->getInvokeArg('referer');
From the Zend docs for Zend_Controller_Front:
7.3.4. Front Controller Parameters
In the introduction, we indicated that the front controller also acts as a registry for the various controller components. It does so through a family of "param" methods. These methods allow you to register arbitrary data – objects and variables – with the front controller to be retrieved at any time in the dispatch chain. These values are passed on to the router, dispatcher, and action controllers.
Zend not have function for this. But simple way, save url in session and use it here
You can use something like:
$current_page_url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

Categories