Kohana Sessions Issue - php

Let me try to explain what I want to do here. I am trying to re-write a pet project from Codeigniter 2.x to Kohana 3.2.x.
I have created a Site Template controller (below)
class Controller_Site_Template extends Controller_Template
{
public $template = 'templates/hero';
/**
* The before() method is called before your controller action.
* In our template controller we override this method so that we can
* set up default values. These variables are then available to our
* controllers if they need to be modified.
*/
public function before()
{
parent::before();
if ($this->auto_render)
{
// Initialize empty values
$this->template->title = '';
$this->template->content = '';
$this->template->session = '';
$this->template->styles = array();
$this->template->footer_scripts = array();
$session = Session::instance();
$this->template->session = $session;
}
}
/**
* The after() method is called after your controller action.
* In our template controller we override this method so that we can
* make any last minute modifications to the template before anything
* is rendered.
*/
public function after()
{
if ($this->auto_render)
{
$styles = array(
'assets/css/style.css' => 'screen',);
$footer_scripts = array(
'assets/js/libs/jquery-1.7.1.min.js',
'assets/js/application.js',
);
$this->template->styles = array_merge( $this->template->styles, $styles );
$this->template->footer_scripts = array_merge( $this->template->footer_scripts, $footer_scripts );
}
parent::after();
}
After the login form is submitted I set the session data and I am able to retrieve the session data in the Controllers that extend the Controller_Site_Template but I am unable to retrieve the session data in any of the View files.
The only way I am able to get the session data in the view files is to pass the session data in each controller that extends the Template_Site_Template:
$this->template->content->set_global('session',$this->template->session->as_array());
Is there an easy way to establish and set the session in the template_controller that can be used in all of the controllers, modelc, views rather that using the set_global on each individual controller?
I don't know if I am explaining this well but I am used to the ease of Codeigniter's $this->session->userdata(); function that can be called in any controller, model, and view once it was set.
Thank you in advance for any input on what I am doing incorrectly.

You can set or bind global data to your views with the following
View::bind_global('session', $session);
View::set_global('session', $session);
If you plan to change any data further along the application logic, then use bind.
If no more changes to the data are required, use set.
Edit: oh, the above is just for views and you want it across the entire application.
Just use the Session::instance()->set() and Session::instance()->get() as required across your application rather then assigning it in your application controller.

Related

Pass Database Values to Layout

In my Zend application there is a layout file used in multiple modules. Now i need to retrieve data from database (table gateway) and display on layout. Then it should appear across all the modules.
How do i achieve that ?
Ex -
<?php echo $user_name; ?>
Value for $user_name should be taken from database and pass to layout file.
you dont have to set it in every controller. You could just attach it to a layout variable in your module.php.
public function onBootstrap(MvcEvent $e)
{
$sm = $e->getApplication()->getServiceManager();
$tableWhatever = $sm->get('tableWhatever');
$viewModel = $e->getApplication()->getMvcEvent()->getViewModel();
$viewModel->userName = $tableWhatever->getUserName();
}
Depending on the zf2 version you may have to access the variable in your layout like so:
$this->layout()->userName;
You also have the possibility to extend the AbstractActionController and add the layout variables trough that. I usually just go with the quick onBootstrap method though.
I believe, in Zend, your controller(s) will want:
$this->view->assign('variableName', 'variableValue');
And in your view(s), you will want:
$this->variableName;
You could use Zend Plugin to achieve something like that, like:
class MyPlugin extends Zend_Controller_Plugin_Abstract {
public function preDispatch(Zend_Controller_Request_Abstract $request) {
// Get instance
$layout = Zend_Layout::getMvcInstance();
$view = $layout->getView();
$view->user_name = 'your_username';
}
}
and register your plugin in frontController:
Zend_Controller_Front::getInstance()->registerPlugin(new MyPlugin());
then in layout , you could do:
<?php echo $this->user_name; ?>

Zend redirect within view helper

Hi i have a following script to redirect within view helper
<?php
class Application_View_Helper_ExistUserRev extends Zend_View_Helper_Abstract{
public function existUserRev($params,$user)
{
$businessReviewMapper = new Application_Model_Mapper_BusinessReviewsMapper();
$businessReviewModel = new Application_Model_BusinessReviews();
$result = $businessReviewMapper->userReviewStatus($user>getUserId(),$params['bzid']);
if($result){
$url = 'http://www.akrabat.com';
$this->_helper->redirector->gotoUrl($url);
}
}
}
?>
But it seems that my above redirect seems not working. How can i redirect within view helper of my zend app? Thanks
As you're in a View Helper class, you can't use $this->_helper->redirector->gotoUrl($url);, this is an Action Controller function.
You have to call the redirector in your View Helper.
Try this :
$_redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
$_redirector->gotoUrl($url);
Redirector is a controller ACTION helper, not a View helper, so you should use it from the controller, not from the view.
To redirect from the view (not a good idea BTW, the logic should stay in the controller, not in the view), try using the Zend Action View Helper
This is even simpler then presented so far:
Excerpt from Zend Framework 1.x reference: Writing Custom Helpers
In general, the class should not echo or print or otherwise generate
output. Instead, it should return values to be printed or echoed. The
returned values should be escaped appropriately.
Basically a view helper should return a value, not perform an action.
Action helpers on the other hand can do pretty much anything you need done.
Here is a very simple example to demonstrate the form of using the direct() method in the helper:
<?php
/**
* Simply returns a search form to a placeholder view helper
*
*/
class My_Controller_Action_Helper_Search extends Zend_Controller_Action_Helper_Abstract
{
/**
* #param string $action
* #param string $label
* #param string $placeHolder
* #return \Application_Form_Search
*/
public function direct($action, $label = null, $placeHolder = null)
{
$form = new Application_Form_Search();
$form->setAction($action);
$form->search->setLabel($label);
$form->query->setAttribs(array(
'placeholder' => $placeHolder,
'size' => 20,
));
return $form;
}
}
here is how it's used in a controller to populate a placeholder helper in either a view script or a layout.
public function preDispatch()
{
$this->_helper->layout()->search = $this->_helper->search(
'/index/display', 'Search My Collection!', 'Search Query'
);
}
and in the view script or layout:
<?php echo $this->layout()->search?>
In your case you might use an action helper to establish the values needed to construct the proper url, then you could pass those value to the url() helper or to a helper of your own construction.

Adding Default Variables to Zend2 ViewModel

What's the "Zend" way of adding default variables to the ViewModel.
Currently I have:
return new ViewModel(array('form' => new CreateUserForm));
But I want to always add some variables to the ViewModel array. Like the time and date say, or categories for a menu. I was thinking of extending the ViewModel as that seems the OO way, but Zend always does things differently...
You could always extend the ViewModel if you want some extra functionality in there...
class MyViewModel extends ViewModel
{
/**
* Default Variables to set
*/
protected $_defaultValues = array(
'test' => 'bob'
);
/**
* Constructor
*
* #param null|array|Traversable $variables
* #param array|Traversable $options
*/
public function __construct($variables = null, $options = null)
{
//$variables = array_merge($this->_defaultValues, $variables);
$this->setVariables($this->_defaultValues);
parent::__construct($variables, $options)
}
}
Now in your controller just use return your new view model instead:
/**
* Some Controller Action
*/
function myAction()
{
return new MyViewModel();
}
One approach could be to have a method in your controller that returns ViewModel populated with time, date, etc. and then addVariables() to the returned model in the Action.
However, a better approach will be to use view helpers since they will be available in every view/layout throughout the application.

Help getting Model into my Controllers, with MVC

I have been working on my own library/framework for the learning experience for a while. MVC is one of those things that took me a while to really understand but I do finally "Get it".
Below is some sample code for a basic MVC setup in PHP. I think I am in the right direction so far, where I need a little help is down in the "Example controller" near the bottom, you will see where I can create a view, I just need to figure out how to best get my data from a model file into that controller class. Please help with example code if you can, hopefully I am making sense.
Also I am welcome to any comments/suggestions on any of the code
Abstract Controller class...
/**
* MVC Example Project
*/
/**
* Extend this class with your Controllers
* Reference to the model wrapper / loader functions via $this->model
* Reference to the view functions via $this->view
*/
abstract class Core_Controller {
protected $view;
protected $model;
function __construct($dependencyContainer){
$this->view = new Core_View();
//$this->view = $dependencyContainer->get(view);
}
}
Abstract Model class...
/**
* Extend this class with your models and reference to the database object via $this->$db
*/
abstract class Core_Model {
protected $db;
protected $session;
function __construct($dependencyContainer) {
$this->db = $dependencyContainer->get(database);
$this->session = $dependencyContainer->get(session);
}
}
View class, might make it abstract as well...
class Core_View {
protected $data;
# Load a view file (views/$view.php);
# $param data this gets extracted and be thus be used inside the view
# When loading another view from inside the view file the data is 'cached' so you
# don't have to pass them again
public function load($view,$data = null) {
if($data) {
$this->data = $data;
extract($data);
} elseif($this->data != null) {
extract($this->data);
}
require(APP_PATH . "Views/$view.php");
}
public function set($data = null) {
if($data) {
$this->data = $data;
extract($data);
} elseif($this->data != null) {
extract($this->data);
}
}
}
Example putting it together...
/**
* Example Controller
*/
class User_Controller extends Core_Controller {
public function profile()
{
$profileData = array();
$profileData = //GET from Model
$this->view->load('userProfile', $profileData);
}
}
?>
My suggestion is not to tie view and model to the controller at all. Let them be instantiable from controller code, just like any other classes. You can then get the model data (and pass it to the view) in standard object oriented way.
Will you use a Data access layer (DAL) / Object-relational mapping (ORM)? Take a look at Zend_Db, Doctrine or Propel
I'd say that you're missing the part of the application that manipulate your models. It could be your controller, but isn't a good practice. So we need a model mapper.
The best way to get model data from your controller is simply calling it. But generally we use a kind of "pointer" which knows how to populate your object model. This pointer is called "Mappers" (Data Mapper Pattern):
$MyModelMapper = new MyModelMapper();
$Profile = $MyModelMapper->getProfileById($id); // return Core_Model.
This function will perform a database query and will populate one specific model with the data. You could also get an array of objects for a "list" action for example.
Then you'll pass this model to your view.
I think you should take a look at the Zend Framewok quick start. It will give you some ideas.
See this question too: What's the difference between DAO and Data Mapper

Zend Unset Action helper from controller action

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
}

Categories