Cakephp using Cache in Component - cakephp

I am using Cakephp 2.3 , i want to perform lots of common calculation in my several controllers. so i write those functions in my appcontroller and i cached some datas..
but what happens is my appController will become fatty.. so i create some component to perform these actions.. i dont know my approach is right or not..? please suggest..
i want to use cache in my component, i tried this code. but nothing is cached..
public $helpers =array('Cache');
and
$result = Cache::read('fm_data', 'long');
if (!$result) {
$result =
$this->TFmStation->find('all',array('contain'=>array('TLocation',
'TLanguage','TMediaOrg','TContactPerson',
'TAddress','TFmProgram'=>array('TTargetGroup'))));
Cache::write('fm_data', $result, 'long');
}
return $result;
please help me to how to use cache in component
how to effectively use component class in cakephp in the case of more common functions in the application.. when i write these functions in appController it load all the functions so according to memory prespective, how to effectively use component

Model TFmStation is best place to have the above logic. Components are there for generic functionality like UploadComponent, EmailComponent, RecaptchaComponent etc. If your logic part have something to do with model, then it should go into that model.
A Model can be called from AppController.php in a similar fashion as you calling your Component.

Related

How to get current controller action in cakephp 3.x model

I am using cakephp 3.x have put database queries in model in which i want to check the current controller action and based on that i will make my database queries.
I know i can pass controller action from my controller itself to my model function but is there a way i can just check my current controller action inside my model only so that i do not need to pass it in my multiple functions which are inside model only.
My Try -- UsersTable.php
public function initialize(array $config)
{
parent::initialize($config);
$this->table('users');
$this->primaryKey('user_id');
echo '<pre>';
print_r($GLOBALS);
exit;
}
so far if i do this, i got an array in response and in which i found this the best result out of other things in that array
[REQUEST_URI] => /5p_group/users/add
I m also trying to use this
echo '<pre>';
print_r($GLOBALS['_SERVER']['HTTP_REFERER']);
exit;
which gives me this output
http://localhost/5p_group/users/archived
so eventually i am getting the result which i want but i want another proper method which cakephp 3.x uses ..
So is there any other way or more frequent way from that i can get my current controller action ?
Any ideas will be appreciated ..
Thanks
First of all you should use the routing class in your model. So at the top you can call it like below
use Cake\Routing\Router;
And then in your initialize function you can check the params like
debug(Router::getRequest());
Or to be more specific you can use
debug(Router::getRequest()->params['action']);
I think this is the solution using cakephp classes only, though a small hack.
For more function reference you can access the cookbook at Router Class
The question was about a Model, but it shows up on Google.
When inside a view (.ctp file), use
\Cake\Routing\Router::getRequest()->getAttributes();
CakePHP 3

Laravel use of the database: where does it need to be placed? In Models or in Controllers?

What is the better place to write out database queries in Laravel?
In Controllers or in Models?
Please let me know which way is correct:
Using in controllers like this?
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB; // <--------
use App\Http\Requests;
use App\Http\Controllers\Controller;
class UsersController extends Controller
{
public function getUser()
{
return DB::table('users')->where('name', 'John')->value('email');
}
}
Using in models like this?
<?php
namespace App\Models;
use DB; // <--------
use Illuminate\Database\Eloquent\Model;
class UsersModel extends Model
{
protected $table = 'users';
public function getUser()
{
return DB::table('users')->where('name', 'John')->value('email');
}
}
Or none of the above?
Academically, it's better to keep all data based logic inside models only. But on practice it's more convinient to keep simple queries inside a controller and use scopes for repeated stuff. You get more readable and easier to maintain code in this case. Also, all Laravel books suggest the same.
Anyway it's more opinion based.
Your usage here is actually better solved with scopes.
use Illuminate\Eloquent\Database\Builder;
use Illuminate\Eloquent\Database\Model;
class User extends Model
{
// Did you know that if your model name is the singular version of your table name, you don't need to include this?
protected $table = 'users';
public function scopeForName(Builder $query, $name)
{
return $query->where('name', $name);
}
}
And now usage is this:
$user = User::forName('John')->email;
The topic of where you should place your queries is a common one. It ultimately comes down to your personal preference and your particular situation.
If you need to reuse the query elsewhere I would recommend placing the query within your model. However, I must warn you that you may encounter problems when using this option because changing the query can have unexpected results, if the query is used in multiple places within your application.
If you do not need to reuse the query, place it within the controller. This way you never have to worry about the query changing and breaking your controller method.
To answer your question, there is no definite place where you should place queries. All I can suggest is don't overcomplicate your solution, and don't try to shoehorn all your queries into one pattern.
There are other options to the two examples you provided though. For more information on these check out these videos:
Scopes, Repos, and Query Objects
The Query Builder

In CakePHP, how do I call an AppController method from a helper?

Follow up question to: In CakePHP, where would I put a method that performs a check on the Session User?
Background: In my previous question, I was informed that the correct place to place a method such as levelCheck() which performs a semi-complicated evaluation of a user's level, and is needed in practically all my controllers, is the AppController.
Now, this method is also incredibly useful for the way I design menu layouts and other view devices. For that reason, I would like to create a helper that can make use of that method.
Problem: I recognize that it's generally frowned upon to call a controller method from the view... however there is no viable way for me to pass data to replicate the function of this method, nor do I want to replicate the method in two places (violating DRY methodology).
Question: How then do I call this method from a helper, or is there a better way to provide use of this method in the view/elements?
Put the method in AppController, also - set a variable that will save the result.
In the beforeRender callback, set the result as a viewVar.
some code:
// AppController
class AppController extends Controller
{
$levelCheckResult = null;
function levelCheck(){
$this->levelCheckResult = true/false;
}
function beforeRender(){
$this->set('levelCheckResult', $this->levelCheckResult);
}
}
that's it, now you can access it in the view.
edit
create a public function in the app_controller, and in the beforeRender(), send the app_controller itself, to the view.
class AppController extends Controller
{
function levelCheck(){
....
}
function beforeRender(){
$this->set('TheApp', $this);
}
}
// in the view
$TheApp::levelCheck();
However, please consider again the design. this kind of manipulation is strongly suggest that you should change some stuff there.
In short - the view is still backend execution of the program and not the client side, so in definition - it should and can be controlled, from the controller...
The solution I ended up using was to move the method to a component (CurrentUserComponent).
From there, it was as simple as calling the component in the head of my helper...
App::uses('CurrentUserComponent', 'Controller/Component');
And referencing the component's static method:
CurrentUserComponent::levelCheck(x,y,z);
I don't think this is entirely within the intention of the MVC pattern, but it doesn't pervert it horribly, and allows access to the method from anywhere in the application.

CakePHP global variables in model

I am making one CakePHP project with Auth component. When I log in I got Session variable with user data. At the moment I am using this variable in controllers to pass data to the model.
$user = $this->Session->read('Auth');
$costs = $this->Posts->get_quartal_cost($user, $quartal, TRUE);
As I am using this in many controllers/models I am thinking that this is not DRY approach, so I wanted to make it better - something in AppModel(?)
Do you have some advice how to do that better?
Thanks
You could use the beforeFilter event in your AppController and do something like this:
public function beforeFilter()
{
if ( $this->Session->check('Auth') )
Configure::write('Auth', $this->Session->read('Auth'));
}
From anywhere in your controllers, models and even views, you'll be able to access it by using echo Configure::read('Auth');. See the Configuration class documentation for more information.

How to load custom plugins in CakePHP?

I'm writing a poll plugin for a website based on CakePHP. The plugin works good if I access it from its own URL (eg. myapp.com/plugin/controller) but I need to call it from different pages. I would like to include it as a widget in every page.
I'm looking for a method like $myplugin->renderPoll($pollId); but I really didn't find any information about how to instantiate the Polls class. I tried with App::import and ClassRegistry::init with no luck.
Any suggestion ?
Thank you
Looks like you are trying to create some sort of Helper to create poll cross views? I would suggest creating a Helper for that particular class. Simply create a helper in plugins/plugin_name/views/helpers/foo.php, and in each controller (or in app_controller.php) that you need it, include the helpers as $helpers = array("PluginName.Foo"); and inside your view, you should be able to use the methods defined in foo.php by calling $foo->renderPoll($pollId).
//app/plugins/plugin_name/views/helpers/foo.php
class FooHelper extends AppHelper {
var $name = "Foo";
function renderPoll($id=0) {
//...
}
}
Use Elements! They're small blocks of presentation code that need to be repeated from page to page, sometimes in different places in the layout.
Check this link out: http://book.cakephp.org/view/1081/Elements
I guess this link explains everything you need.

Resources