Im using Zend Framework 3 and the SessionManager and im trying to build a controller plugin / view helper to display confirm dialogues after validating some Data . The idea was simply to set a Session variable with everything the confirm dialogue needs, reading it by the view, and unsetting it. But even this simple cycle fails. The plugin basically does this when invoked by the controller:
$dataArray = [
'some_data' => 'data'
];
$this->sessionManager->getStorage()->confirmDialog = $dataArray;
in the layout.phtml i call my view Helper which does this:
public function __invoke() {
$data = $this->sessionManager->getStorage()->confirmDialog;
$this->sessionManager->getStorage()->clear('confirmDialog');
return $this->getDialog($data);
}
I do inject the sessionManager to both the plugin and the view helper. When not clearing the variable after receiving its data i get the changed data from the session variable and it gets updated by the Plugin as it should.But when clearing the variable after the first time reading it, its always empty.
Here my global.php setup:
'session_manager' => [
'validators' => [
RemoteAddr::class,
HttpUserAgent::class,
]
],
'session_storage' => [
'type' => SessionArrayStorage::class
]
Because the value is passed by reference, when you clear it, you clear the read information with it also.
As I mentioned in a comment, I suggest using the default falsh messenger plugin, but if you want to create your own plugin, here is a hint from that's source code, which shows you how you can achieve a default clear after read from session.
https://github.com/zendframework/zend-mvc-plugin-flashmessenger/blob/843654a029a19c38e0c3b2e940e59edec75c3e4f/src/FlashMessenger.php#L165
This setting is actually tells the session container to drop that information after '1 hop', ie. in case of a next request.
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 have problems to get cookies to work in cakephp 3.5.x.
in earlier versions I've used the Cookie component but this is now deprecated. Its unclear for me how to use this new middlewarestuff for reading and writing cookies.
The documentation is unclear for me. It shows me how to set up the cookie middleware but not how to handle creating cookies in a controller. Is there anyone who has handled cookies in 3.5.x?
The middleware only replaces the encryption part of the Cookie component (which basically is the only thing it did as of CakePHP 3.0 anyways), if required it automatically encrypts and decrypts the cookies that you've configured.
You do not use the middleware to read or write cookies, that is done via the request and response objects, which is the default since CakePHP 3.
Reading and writing cookies from within a controller action can be as simple as:
$rememberMe = $this->request->getCookie('remember_me');
$this->response = $this->response->withCookie('remember_me', [
'value' => 'yes',
'path' => '/',
'httpOnly' => true,
'secure' => false,
'expire' => strtotime('+1 year')
]);
See also
Cookbook > Controllers > Request & Response Objects > Request > Cookies
Cookbook > Controllers > Request & Response Objects > Response > Setting Cookies
Cookbook > Controllers > Request & Response Objects > Cookie Collections
My case using Cake 3.8, just in case someone is lost as myself:
In your beforeFilter load the component
public function beforeFilter(Event $event)
{
parent::beforeFilter($event);
//Load components, like Cookie
$this->loadComponent('Cookie', ['expires' => '30 day']);
}
If cake complains:
Argument 1 passed to App\Controller\PController::beforeFilter() must be an instance of App\Controller\Event, instance of Cake\Event\Event given
Add the following to the top of your class:
use Cake\Event\Event;
And then reading and writing Cookies in your Controller action is breeze:
//Read
$fooVal = $this->Cookie->read('foo');
//Write
$this->Cookie->write('foo', 'bar');
I wanna use smarty template engine in yii2.
In my project, i need load view codes from database and render them from controller.
My question is this:
Is there any way to render a view code from string and control it like common render?
i need something like below:
$this->renderAsString($templateStr, ['param1'=>$val1, 'param2'=>$val2]);
this is important for me can access variable and function like as below code in index.tpl file.
$this->render('index.tpl'['param1'=>$val1, 'param2'=>$val2]);
I read this http://www.smarty.net/docs/en/resources.string.tpl but my answer is different, i think.
There is special separate extension called yii2-smarty for rendering views with Smarty. You need to install it via Composer, then configure like this for usage:
return [
//....
'components' => [
'view' => [
'renderers' => [
'tpl' => [
'class' => 'yii\smarty\ViewRenderer',
//'cachePath' => '#runtime/Smarty/cache',
],
],
],
],
];
As for your specific problem, look at these two issues on Github:
Add ability to render view from string
View renderer from db - not implemented yet
Core developer Klimov Paul recommends to use eval, but also in Smarty dedicated function exists exactly for these kind of situations.
Example 8.4. Another {eval} example
This outputs the server name (in uppercase) and IP. The assigned
variable $str could be from a database query.
<?php
$str = 'The server name is {$smarty.server.SERVER_NAME|upper} '
.'at {$smarty.server.SERVER_ADDR}';
$smarty->assign('foo',$str);
?>
Where the template is:
{eval var=$foo}
I'm having problem using trans() function in config file, I feel it not supposed to be used that way. However I've no clue on what would be the most efficient way to translate string text in config files (files in /config folder).
Original code
<?php
return [
'daily' => 'Daily'
];
When I try to implement trans() application crashes and laravel return white page without any error messages
<?php
return [
'daily' => trans('app.daily_text')
];
The config files are one of the first stuff Laravel initialize, it means you can't use Translator nor UrlGenerator inside a config file.
I don't know what you are trying to do, but you shouldn't need to use Translator inside a config file though...
You cannot not use trans or route method inside the Laravel config file. At the time the config file is loaded, these methods are not available to run. Also, the purpose of the configuration file is used for storing pure value and we should not trigger any actions inside the configuration file.
I know sometimes you want to put things into config file with dynamic data generated from route or text from language key. In my usecase is: configure the menu structure inside the config file. On that case, you should choose the approach of: storing only the translation key and an array which include information that you can generate the URL at run time.
I put my gist here for you to look up on the approach.
You can just store the key in config file like and then use the trans function in the view to get the translations:
Config file:
<?php
return [
'foo' => 'bar'
];
Then in the view:
{{ trans(config('config.foo') }}
I don't know if this is good practice but I ended doing this in my similar situation.
Config.php:
'Foo' => array('
'route' => 'route.name',
'name' => 'translated_line', //translated in lang file ex. /en/general.php
'),
Then in the view I used:
{{ Lang::get('general.'.Config::get('foo.name'))) }}
Maybe this is too late but I posted it here anyway so that maybe someone will find it useful, like me :))
As of Laravel v5.4, you can use the __ helper function to access the translations after Laravel has booted.
Example:
config/example.php
<?php
return [
'daily' => 'Daily',
'monthly' => 'app.monthly_text',
'yearly' => 'app.yearly_text'
];
resources/lang/en/app.php
<?php
return [
'monthly_text' => 'Monthly'
];
You can access the translations like so:
<?php
// ...
$daily = config('example.daily');
$a = __($daily); // "Daily"
$monthly = config('example.monthly');
$b = __($monthly); // "Monthly"
$yearly = config('example.yearly');
$c = __($yearly); // "app.yearly_text"
Currently after login Lithium stores in session and cookies all rows from users table like password, hash etc. How to remove (don't allow to store) some of the information like password and hash?
The Session class stores what you tell it to! After Auth::check is done, you should only store the session identifier and/or absolutely necessary data in the cookie. Also make sure to use the Encryption provided by lithium (AES) out of the box.
For more detailed help, please post your login controller and all appropriate model/filters.
Passing options to Auth::check will get passed down to the adapter as well (plus some extras) -- for this I'm assuming you're using the Form adapter for the Auth class.
Try doing this when you perform your check: Auth::check('config', $data, array('fields' => array('fields', 'you', 'want'))
The key here is that array we tacked on the end with the fields key in it, this will be passed down to the Form adapter which takes in those options and uses them to query your model for a matching user. By telling it explicitly which fields to return, it will only pass those back to the Auth class for storing away.
Since this commit you can pass an option 'persist' => array('field1','..') to Auth::check, or set them as default in your bootstrap session config, to store only specified fields.
So either you set this in your bootstrap/session.php
Auth::config(array(
'user' => array(
'adapter' => 'Form',
'session' => array(
'persist' => array('_id','username')
),
'model' => 'Users'
)
));
or you define the fields, when calling Auth::check() - this will override everything from the config above!
Auth::check('user', $this->request, array(
'persist' => array('username','email')
))
Note: If not defined explicitly the password is never stored by default.