CakePHP reaching cookies from the view files - php

I need to reach my cookies from the view files. I'm aware that one can use CookieComponent inside a controller and pass cookie values to view files with set().
Visitors of our website has an options page. User's selections are saved to cookies. Up to now I was using CookieComponent and checking the values and making my works with that values. But now I added new options choices, so I need to reach them from my view files, or from my helpers. If I pass cookie values from the controller to view, I must do that for each of my action and I don't prefer it. Also it will make more complex code.
I saw this question and that question. (Also it is possible to read them with $_COOKIE[<cookie_name>], but that solution can't be used for encrypted cookies. My cookie is not encrypted but it can be in future)
My question is why there is no CookieHelper in the Cake's libs ? Is that a bad practice to reach cookies from the view files ? Is there a methodical way to reach cookies from views ? For example writing a custom helper that uses $_COOKIE and use that helper ?

Passing the data from the controller is an appropriate way of doing this.
If you need the data in many/all views, use the Controller::beforeFilter() callback, that way the variable is available to all views rendered by the specific controller:
class MyController extends AppController
{
// ...
public function beforeFilter()
{
parent::beforeFiler();
$this->set('cookie', $this->Cookie->read('cookie'));
}
// ...
}
Just make sure that possible cookie component configuring is done before reading the cookie!

I believe you can access it via the SessionHelper:
echo $this->Session->read($cookieName);

You can read cookie by help of javascript if this does not work use ajax calls to read cookies on document load and implement your logic by returning via json.

Related

Dealing with Views in Phalcon Controllers

I am working on a newly created Phalcon project, and I don't really know how to actually use multiples views.
What is the entry point? I don't really know when each method in the controller is called, under which conditions, etc.
Where is the control flow defined? is it based in the name of the view? or is there a place where you can register them?
Phalcon is a bit different than other well-known PHP frameworks, in that not much is pre-configured or pre-built by default. It's quite loosely-coupled. So you have to decide where and how your control flow will work. This means that you will need to dig deeper in the documentation and also that there could be different way to achieve the same thing.
I'm going to walk you through a simple example and provide references, so you can understand it more.
1) You would start by defining a bootstrap file (or files) that will define the routes, or entry points, and will setup and create the application. This bootstrap file could be called by an index.php file that is the default file served by the web server. Here is an example of how such bootstrap file will define the routes or entry points (note: these are just fragments and do not represent all the things that a bootstrap file should do):
use Phalcon\Di\FactoryDefault;
// initializes the dependency injector of Phalcon framework
$injector = new FactoryDefault();
// defines the routes
$injector->setShared('router', function () {
return require_once('some/path/routes.php');
});
Then it the routes.php file:
use Phalcon\Mvc\Router;
use Phalcon\Mvc\Router\Group as RouterGroup;
// instantiates the router
$router = new Router(false);
// defines routes for the 'users' controller
$user_routes = new RouterGroup(['controller' => 'users']);
$user_routes->setPrefix('/users');
$user_routes->addGet('/show/{id:[0-9]{1,9}}', ['action' => 'show']);
$router->mount($user_routes);
return $router;
Im defining routes in an alternate way, by defining routes groups. I find it to be more easy to organize routes by resource or controller.
2) When you enter the url example.com/users/show/123, the routes above will match this to the controller users and action show. This is specified by the chunks of code ['controller' => 'users'], setPrefix('/users') and '/show/{id:[0-9]{1,9}}', ['action' => 'show']
3) So now you create the controller. You create a file in, let's say, controllers/UsersController.php. And then you create its action; note the name that you used in the route (show) and the suffix of Action:
public function showAction(int $id) {
// ... do all you need to do...
// fetch data
$user = UserModel::findFirst(blah blah);
// pass data to view
$this->view->setVar('user', $user);
// Phalcon automatically calls the view; from the manual:
/*
Phalcon automatically passes the execution to the view component as soon as a particular
controller has completed its cycle. The view component will look in the views folder for
a folder named as the same name of the last controller executed and then for a file named
as the last action executed.
*/
// but in case you would need to specify a different one
$this->view->render('users', 'another_view');
}
There is much more stuff related to views; consult the manual.
Note that you will need to register such controller in the bootstrap file like (Im also including examples on how to register other things):
use Phalcon\Loader;
// registers namespaces and other classes
$loader = new Loader();
$loader->registerNamespaces([
'MyNameSpace\Controllers' => 'path/controllers/',
'MyNameSpace\Models' => 'path/models/',
'MyNameSpace\Views' => 'path/views/'
]);
$loader->register();
4) You will also need to register a few things for the views. In the bootstrap file
use Phalcon\Mvc\View;
$injector->setShared('view', function () {
$view = new View();
$view->setViewsDir('path/views/');
return $view;
});
And this, together with other things you will need to do, particularly in the bootstrap process, will get you started in sending requests to the controller and action/view defined in the routes.
Those were basic examples. There is much more that you will need to learn, because I only gave you a few pieces to get you started. So here are some links that can explain more. Remember, there are several different ways to achieve the same thing in Phalcon.
Bootstrapping:
https://docs.phalconphp.com/en/3.2/di
https://docs.phalconphp.com/en/3.2/loader
https://docs.phalconphp.com/en/3.2/dispatcher
Routing: https://docs.phalconphp.com/en/3.2/routing
Controllers: https://docs.phalconphp.com/en/3.2/controllers
More on Views (from registering to passing data to them, to templating and more): https://docs.phalconphp.com/en/3.2/views
And a simple tutorial to teach you some basic things: https://docs.phalconphp.com/en/3.2/tutorial-rest
The application begins with the routing stage. From there you grab the controller and action from the router, and feed it to the dispatcher. You set the view then call the execute the dispatcher so it access your controller's action. From there you create a new response object and set its contents equal to the view requests, and finally send the response to the client's browser -- both the content and the headers. It's a good idea to do this through Phalcon rather than echoing directly or using PHP's header(), so it's only done at the moment you call $response->send(); This is best practice because it allows you to create tests, such as in phpunit, so you can test for the existence of headers, or content, while moving off to the next response and header without actually sending anything so you can test stuff. Same idea with exit; in code, is best to avoid so you can write tests and move on to the next test without your tests aborting on the first test due to the existence of exit.
As far as how the Phalcon application works, and in what steps, it's much easier to follow the flow by looking at manual bootstrapping:
https://docs.phalconphp.com/en/3.2/application#manual-bootstrapping
At the heart of Phalcon is the DI, the Dependency Injection container. This allows you to create services, and store them on the DI so services can access each other. You can create your own services and store them under your own name on the DI, there's nothing special about the names used. However depending on the areas of Phalcon you used, certain services on the DI are assumed like "db" for interacting with your database. Note services can be set as either shared or not shared on the DI. Shared means it implements singleton and keeps the object alive for all calls afterwards. If you use getShared, it does a similar thing even if it wasn't initially a shared service. The getShared method is considered bad practice and the Phalcon team is talking about removing the method in future Phalcon versions. Please rely on setShared instead.
Regarding multiple views, you can start with $this->view->disable(); from within the controller. This allows you to disable a view so you don't get any content generated to begin with from within a controller so you can follow how views work from within controllers.
Phalcon assumes every controller has a matching view under /someController/someView followed by whatever extension you registered on the view, which defaults to .volt but can also be set to use .phtml or .php.
These two correspond to:
Phalcon\Mvc\View\Engine\Php and Phalcon\Mvc\View\Engine\Volt
Note that you DON'T specify the extension when looking for a template to render, Phalcon adds this for you
Phalcon also uses a root view template index.volt, if it exists, for all interactions with the view so you can use things like the same doctype for all responses, making your life easier.
Phalcon also offers you partials, so from within a view you can render a partial like breadcrumbs, or a header or footer which you'd otherwise be copy-pasting into each template. This allows you to manage all pages from the same template so you're not repeating yourself.
As far as which view class you use within Phalcon, there's two main choices:
Phalcon\Mvc\View and Phalcon\Mvc\View\Simple
While similar, Phalcon\Mvc\View gives you a multiple level hierarchy as described before with a main template, and a controller-action based template as well as some other fancy features. As far as Phalcon\Mvc\View\Simple, it's much more lightweight and is a single level.
You should be familiar with hierarchical rendering:
https://docs.phalconphp.com/en/3.2/views#hierarchical-rendering
The idea is with Phalcon\Mvc\View that you have a Main Layout (if this template exists) usually stored in /views/index.volt, which is used on every page so you can toss in your doctypes, the title (which you would set with a variable the view passed in), etc. You'd have a Controller Layout, which would be stored under /views/layouts.myController.volt and used for every action within a controller (if this template exists), finally you'd have the Action Layout which is used for the specific action of the controller in /views/myController/myAction.volt.
There are all types of ways you can break from Phalcon's default behavior. You can do the earlier stated $this->view->disable(); so you can do everything manually yourself so Phalcon doesn't assume anything about the view template. You can also use ->pick to pick which template to use if it's going to be different than the controller and action it's ran in.
You can also return a response object from within a controller and Phalcon will not try to render the templates and use the response object instead.
For example you might want to do:
return $this->response->redirect('index/index');
This would redirect the user's browser to said page. You could also do a forward instead which would be used internally within Phalcon to access a different controller and/or action.
You can config the directory the views are stored with setViewsDir. You can also do this from within the controller itself, or even within the view as late as you want, if you have some exceptions due to a goofy directory structure.
You can do things like use $this->view->setTemplateBefore('common') or $this->view->setTemplateAfter('common'); so you can have intermediate templates.
At the heart of the view hierarchy is <?php echo $this->getContent(); ?> or {{ content() }} if you're using Volt. Even if you're using Volt, it gets parsed by Phalcon and generates the PHP version with $this->getContent(), storing it in your /cache/ directory, before it is executed.
The idea with "template before" is that it's optional if you need another layer of hierarchy between your main template and your controller template. Same idea with "template after" etc. I would advise against using template before and after as they are confusing and partials are better suited for the task.
It all depends on how you want to organize your application structure.
Note you can also swap between your main template to another main template if you need to swap anything major. You could also just toss in an "if" statement into your main template to decide what to do based on some condition, etc.
With all that said, you should be able to read the documentation and make better sense of how to utilize it:
https://docs.phalconphp.com/en/3.2/api/Phalcon_Mvc_View

How to use variable from routes.php in controller

In CakePHP have a bunch of unique URL names redirected in routes.php file.
Similar to this:
$beautiful_urls[0] = '/view/location-name/image-name.html';
Router::connect($beautiful_urls[0],
array('controller' => 'Foo','action' => 'bar',3,60));
I want to create facebook like buttons based on the beautified names. In order to do that I need the $beautiful_urls variable I use in the routes.php in the Foo controller.
How can I reach a variable in routes.php from a controller?
So far I tried to link it with App::use('routes','Config'); but it's not working. I also thought about sending the values as action parameters, but that doesn't seem like good practice... I know it's not a great idea to mix the config file with a controller's logic but I don't have any better idea so far.
I'm not cakephp user but simple search shows that there is class called ClassRegistry.
You can create class BeautifulUrls and store it there. According to docs it's singleton and It can be accessed from everywhere.
Also you can make BeautifulUrls implement ArrayAccess interface so you don't have to change your routes
I don't know if it's a good practice or not but my solution was to use the Configure class of CakePHP. It was straightforward to use and accessible everywhere in the code and the config files.
You can save key-value pairs with
Configure::write('key','value');
and read it again with
Configure::read('key');

Any way to access action variables from an admin generated partial in Symfony 1.4?

I've got a partial that I'm using in a Symfony 1.4 admin generated module but I have some logic that I would prefer to keep in my action. Is there anyway to access action vars in the partial? In a regular template (ie: non admin generated), I could simply declare my var in my action as $this->myVar and then access it from within my template as $myVar, but is there any way to do this in an admin partial?
I've tried declaring it in my preExecute() method but the var is undefined in my partial template.
Am I doing something wrong, or is my only choice to use a component instead of a partial?
Partials and components don't have automatic access to action variables. They only see variables which are explicitly passed to them. In an admin generator module they usually get some useful parameters (e.g. the current object, helper object, configuration, form) but it depends on the current place of invocation (you can see the generated templates in the cache directory to find out which parameters they get). Partials also have access some global objects (e.g. request, user, response,...) which are available in every template file. You can use e.g. request attributes or slots:
// in an action
$this->getResponse()->setSlot('my_slot', $myVariable);
// in a partial
<?php include_slot('my_slot'); ?>
// or
<?php $my_variable = get_slot('my_slot'); ?>
But I think using a component is a better idea.
When you call this partial try to put the variable as a second parameter (or array of parameters) in the include_partial().

Zend Framework application with login and signup pages on one domain and other pages on the subdomain

We develop a zend framework application and want that signup pages and login pages were on our domain for example http://domain.com (now all pages are on http://domain.com) and other pages (where you have to be redirected after authentification) on subdomain: http://subdomain.domain.com.
Could you please tell how to solve it?
Thank you for any ideas.
I've done this kind of thing in a major ZF app of mine. It's a complicated 3-part question, but hopefully this will get you started in the right direction.
First is the session cookie. You'll need to use a wildcard domain parameter when you set the session cookie. In your Bootstrap or somewhere prior to when you would normally start your session, include a line such as:
Zend_Session::start(array('cookie_domain' => '.domain.com'));
Note the dot (".") prior to "domain.com". This makes the cookie applicable for domain.com as well as all subdomains under it.
Second is the URL's throughout your site. You can use the Redirector action helper's gotoUrl() method. At the end of an action method when you want to redirect the user, use a line like this:
$this->_redirector->gotoUrl('http://domain.com/somewhere/else');
Of course, you may want to assemble the URL string by other means such as storing the domain in a configuration parameter and concatenating the path using one of ZF's native methods of generating a URL path. See the documentation for Zend_Controller_Action_Helper_Redirector for more. You'll also need to be careful about all URL's on your site and make sure the right domain is included in each link.
Third is how your app interprets routes when subdomains are involved. There are a few ways to accomplish this, but one is to create a module within your app that corresponds to each subdomain you want to use. Then use a Controller Plugin to intercept ZF's normal routing mechanism and set the module name appropriately based on the subdomain. Something like:
class My_Controller_Plugin_RouteMySubdomains extends Zend_Controller_Plugin_Abstract {
public function routeShutdown(Zend_Controller_Request_Abstract $request) {
$hostname = $request->getHttpHost();
if (strlen($hostname) > strlen('domain.com')) {
$moduleName = preg_replace("/\.domain\.com$/", '', $hostname);
$request->setModuleName($moduleName);
}
}
}
You'll need to tell ZF to use this plugin. If you're using Zend_Application with an application.ini file for basic configuration, you'll need to add a line like this:
resources.frontController.plugins.routeMySubdomains = "My_Controller_Plugin_RouteMySubdomains"
Good luck!

CakePHP: Accessing session data from within a controller

I have an edit action in the users controller. What I want to do is redirect anyone to a different action if their Auth.User.id does not equal the id of the user they are trying to edit.
I can access variables in my views like this:
if($session->read('Auth.User.id') != $id){
but this doesn't work in my controller. Getting:
Undefined variable: session
How do I access session data within a controller? also, if any has a better way of achieving what I want to do, feel free to add!
Thanks,
Jonesy
You must first add Session as a component in your controller:
var $components= array('Session');
You can then access it in your methods via $this->Session
You can read Session data in a controller with $this->Session->read('Auth.User.id'); The CakePHP Session component, if I remember correctly, is automatically loaded into all controllers unless you have defined the default components elsewhere. If $this->Session is undefined, include it into your $components array in your controller like var $components = array('Session');
It's important to note that Helpers are not the same as Components. Generally speaking, Components are extended functionality for your Controller. Whereas Helpers are extended functionality for your view.
For a complete look at all possible methods, the CakePHP Cookbook will be invaluable for you! http://book.cakephp.org/view/1310/Sessions

Categories