Can i call .ctp file from another model in cakephp? - cakephp

I want to call a .ctp file in one 'Model' and the .ctp file is in another 'View'.
Is it possible in cakephp?
Or instead of that should i call that 'Controller' function in my 'Model'?

CakePHP in a nutshell, and the keywords that you might need to search for:
Dispatcher and Routing controlling how URL reaches your controller.
Controller places system logic and controlling individual routing requests from Dispatcher
Component places logics that can be easily shared by Controllers
Model is for all the database related queries, manipulation, selections, deletions
Behavior can be deem as similar to Component, that provides "mixins" to Models to achieve similar behaviors, such as TreeBehavior abstract your database tables into parent-child relationship.
View is used by Controller to render individual pages to the user
Helper placed shared functionalities to help View render certain stuff. For example, FormHelper helps you all sort of form rendering, inputs, etc.
Place globally shared library in app/Lib folder so it can be easily accessed through using App::uses('...', 'Lib'). For example, a Gravatar library that helps you convert emails to md5-hashed strings. So this can be used everywhere in your app.
vendors are for those packaged vendor libraries that do not respect MVC, for example, swiftmailer that helps you send emails. Usually I would abstract them into my Lib folder for ease.
plugins are for those baked CakePHP applications found everywhere in the internet.
There are others in-depth stuff that you might be interested in, but these are the most basic stuff that you need to know before using a MVC framework like CakePHP. Check out their docs before diving in.

You can't access View (.ctp) in Model, it's against MVC architecture and logic. Just tell us more what do you want to do, maybe you're doing something wrong.

Related

Controller logic in Element View in CakePHP

I'm working on a really big project. The aspect I'm currently working on requires that email templates are sent to a user when they're added to a learning course by another user.
The controller that deals with the request, does a bunch of str_replace tasks to find variables in the text (which the user can edit before adding another user to the learning course) and then replaces it with some values in the DB.
I took over this project and I'm not happy with the way half the things are done but time costs dictate I rather just go along with it.
The email is sent using Cake's native email function. It uses a template to capture data and send to the user.
Here's the question:
Should I keep the logic in the controller or do you think it's safe to move it to the element view's .ctp file?
My first instinct is to leave it in the controller as per the usual MVC separation ideals.
Cheers
This is a very important question - what are you using exactly for the email? The old email component or the new CakeEmail class? Which CakePHP core version are you using?
Here are some plausible aproaches here. You can:
Set all those variables, pass them to the view and do all the "replacing" there.
Encapsulate this logic in a component, attach it to your controller(s) and use it.
Just leave it in a private function within the controller and call that function whenever needed. (not really MVC)

Best way to implement admin panel in CakePHP

I am trying to move from CodeIgniter to CakePHP and can't figure out the best way to implement an admin panel. In CI I would create two different applications, one for the frontend and one for the admin panel.
After Googling around, I have found three ways to implement admin panel in CakePHP:
Routing - I don't want to use this as I want by Controllers/Models to be separate for frontend and admin panel
Plugin
Two separate apps
Should I use plugin to implement admin panel or should I have separate apps? Any benefits of one over the other?
I normally develop the admin/backend as a plugin. This keeps your backend/admin controllers/views/models separated from the frontend and you don't have to jump through hoops to have separate stylesheets, layouts etc.
Another advantage is that both front- and backend are still part of the same application, so if desired, you can share logic/components, for example you'll be able to put helpers that are usable both for front- and backend in another plugin (e.g. plugins/Shared or plugins/Handytexttools) and use those both wherever you want
As a rule of thumb; put components that may be reuseable for other projects in a separate plugin, this way you can just add those plugins to other projects without problems. Keep your plugins simple; it's no problem to create a plugin containing just one or two helpers or models and a few files of JavaScript. This will make it easier to 'cherry pick' the plugins that you need for a project. Once Cake has 'cached' the file-locations of all classes in your plugins, the overhead of separate plugins should be minimal.
Coming back to the 'admin' plugin. Try to only include code specific for this project in your admin plugin and reusable parts in another one (e.g. Generic stylesheets and layouts for admin-panels). You'll be able to start a admin-plugin for your next project with minimal coding
Good luck with your project and enjoy CakePHP
If you want to keep your controllers and models separate - I'd go with a separate app, although you'll end up with a bunch of duplicate code between the apps (maintenance headache waiting to happen).
My choice would be admin routing and an admin theme.
Enable admin routing in /app/Config/core.php
In AppController beforeFilter():
$this->theme = isset($this->params['admin']) ? "Admin" : "Site";
Move all your site views and assets into /app/View/Themed/Site/
Create your admin themes in /app/View/Themed/Admin
Old and refers to CakePHP 1.3, but still is a question you should check: CakePHP admin panel
The Cake way is routing. I'd go with a plugin like CakeDC Users that makes things easier.
You could use admin-routing. Check out:
http://book.cakephp.org/2.0/en/development/routing.html#prefix-routing
Another solution -which I find really easy to implement- is like this:
In your AppController:
public function beforeFilter(){
$this->set('current_user', $this->Auth->user());
}
This makes the $current_user available in your app.
Then in your view-files, you can check:
<?php if ($current_user['role'] == 'admin'){/*place code for admin users to see here*/} ?>
<?php if ($current_user){/*place code for logged-in users to see here*/} ?>
I know this is an old thread. But would like to ask if anyone had trouble implementing the admin panel as a plugin. Particularly duplication of code.
For example you're implementing an e-commerce site. You have an OrderController both in the main and admin plugin. Don't you think it's kinda hard to maintain the logic in two places?
How about just using one main controller. It's serves two purpose. One as an API then the controller for your Admin webapp.
Your public side would then basically communicate via API to fetch data.
Do you think it's a good idea?
You can use admin views like admin_index.ctp just change this
//Configure::write('Routing.admin', 'admin');
to
Configure::write('Routing.admin', 'admin');
in core.php and in the controller add admin_index() function

Best Practice for Adminpanel with Acl?

I´m just working with Cakephp for a few days and I´m very impressed. But now I´m trying to get closer with Acl, but it´s a bit confusing.
My situation is, that I want to create a website with a frontend and a backend. But I´m not sure if I really need Acl for this, cause all Pages should be available for all users, except the backend of course. The tutorials in the Cookbook aren´t very helpful due to the fact, that it´s all about creating users, and groups and roles and creating the right views for login, adding and editing users, etc.
But I just need information about what Acl handles? Does it restrict the use of controllers or models?
Or do I need something else than Acl? Maybe it´s easier to check a session variable and redirect direct into the controller if the check false?
Hopefully you can bring me on the right way,
thanks in advance and best greetings from Germany,
Sascha
I suggest you to read this chapter and use the Auth component instead of simply accessing the session as you're teased to do.
http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html
For your admin backend use prefix routing.
http://book.cakephp.org/2.0/en/development/routing.html#prefix-routing
In conjunction with auth this is pretty easy to check and implement in the isAuthorized() callback.
If you don't need various 'levels' of permissions; i.e. any logged-in user is allowed to access the backend, it's best to skip ACL (for now). If, in a later stage, ACL is required, you can always add it later.
You can start with 'simple' authentication. This chapter in the cookbook describes how to do so;
http://book.cakephp.org/2.0/en/tutorials-and-examples/blog-auth-example/auth.html
In general, do not develop features that you don't need now. E.g. implementing ACL because you might need it in the future is only overcomplicating your development and chances are, they don't fit the requirements when that moment arrives.
Unlike #burzum, I'm not a big fan of prefix routing (only for very simple projects), because you'll end up mixing front- and backend actions and logic in the same controller.
I would advice to create separate controllers for the backend, possibly develop them as a Plugin. Either way, you may consider to create 'base' Controllers and Models for the backend and have your backendcontrollers/models extend them. This way you'll be able to define components/behaviors to use for the backend in 1 location. Also, by loading the 'Auth' component only in Backend controllers, you don't have to 'allow' actions in each controller in the frontend
for example;
class BackendCoreController extends AppController {
// only load the Auth component in backend controllers
// regular/frontend controllers don't require authentication
$components = array('Auth');
}
class PageAdminController extends BackendCoreController {
}
For considerations on developing the backend as a plugin, see my answer here:
Best way to implement admin panel in CakePHP

cakephp plugin model/controller cache issue with main model/controller

I have a plugin with user model, profile model and an user controller, in this user model is associated with profile model. In my main model folder (under app), I have user model and user controller(here I have not associated with profile). Sometimes I'm getting errors saying that user model is not associated with profile model. Also sometimes I'm getting the error - "missing action logout in users controller". I have given the logout action in the app/controller/userscontroller but that method is not available in myplugin/usercontroller. Im using cakephp2.0.. How can I solve this issue ? How cakephp is setting the cache for models and controllers ? I don't want to completely disable the cache.
I've had trouble with this as well. Basically it comes down to the fact that Cake doesn't support controllers with the same class name. So a controller named UsersController on plugin and app level will cause trouble with caching and some components (the Auth component, for example).
Support for identical classnames in various levels of a Cake application will come in Cake 3.0 which will require PHP 5.3, which in turn supports namespaces, a feature needed for correctly handling duplicate class names.
With no word on when Cake 3.0 will be released as the 2.0 branch is just out of beta, I refactored my plugin by prepending the plugin name to my controllers, views and models.
So UserModel became PluginUserModel and UsersController became PluginUsersController. It's a bit of a hassle, because you have to update all the views and variables which use the model's name.
My original question contains some links to the Cake bug tracker where similar questions were raised, should you be interested in some background,

How to access models in PagesController--or how to create a dashboard with CakePHP

I have an order processing and catalog system created in CakePHP. It manages orders, products, packages, invoices, etc. (anything that would be necessary for an ecommerce store basically).
I now want to make a "dashboard"-type page, that will show the latest orders, products that need to be updated, latest reviews, etc. I was going to create a Page for PagesController, but I don't know how to access models in PagesController.
Is there any way to access several, unassociated models on one page?
How to build a “dashboard” for your application in CakePHP.
I was going to create a Page for PagesController, but I don't know how to access models in PagesController.
With the built-in PagesController, you can't. You'll have to create your own PagesController, which would look something like this pastebin.
Another way to create such a portal page would be to create a Page for display via the built-in PagesController, the view for which would comprise a variety of view elements, each using requestAction to retrieve their respective data. This can be a tricky approach if you don't or can't employ caching, because requestAction is not very performant, as it begins a new dispatch cycle every time it's called. However, in conjunction with good, aggressive caching, this is a very modular approach, and very Cake-y, since it encapsulates each element of your dashboard's functionality in its own MVC element.
Edit: just to be extra-clear, if you cannot cache the dashboard's elements well, you want to avoid the requestAction route. It's just horrifically slow, and it's better to use an approach such as that in balcer's link, though it is perhaps not as elegant.

Resources