CakePHP multiple controllers using same method - cakephp

I have a method (the function in the controller, am I terming that correctly?) and view that I want to use in every controller on my site. Is there a way to make the method global across all controllers and the view .ctp file generic as well? I'd rather not have to copy-paste it everywhere.
This seems like something that should be obvious, so if I'm just searching for the wrong terms, let me know.
Thanks

Shared/Common Controller Code:
What you've described is a "Component":
Components are packages of logic that are shared between controllers.
If you find yourself wanting to copy and paste things between
controllers, you might consider wrapping some functionality in a
component.
See: http://book.cakephp.org/2.0/en/controllers/components.html
Shared/Common View Code:
As far as the View is concerned, there are a few options. If you want the entire view, you can just specify which view to render: $this->render('TestView/index');
Or, if you want a small chunk of code, you can try an Element.
All together:
If you find yourself creating a lot of the different "parts" (View, Controller/Component, Model/Behavior)...etc, all for the same general purposes (ie cropping a photo), you could think about creating a Plugin.
Side note:
Side note: Usually, I've heard the functions in Controllers referred to as "actions", and the functions in Models called "methods". They're all really methods (a function within a class/object), but - that's how they're commonly referred to.

You can put the method in AppController and make only one view.
You will use $this->render('/myview.ctp');

Related

Custom logic in Cakephp 3.0 view

This is for CakePHP 3.0
I want to encapsulate some nontrivial php logic to be called (reused) several times within one .ctp file for one controller action. I'm trying to figure out the most elegant way of doing it.
I have a few thoughts, none of which seem very elegant:
$this in the CTP file execution context is class View. Put methods on the View class to call as $this->function() within the .ctp file. This seems like the wrong division of labor, especially since helpers seem designed for this. Plus the functions would be exposed to all ctp files.
Create a helper. This seems like the "best" way to go, but that helper is always loaded and exposed to all .ctp files, which seems like it violates containment since the logic is only relevant to one action's view. In the absence of a better solution, this is the route I'm taking.
Create a subclass of View for this element/model and put the logic there, to be accessed as in (1). This seems like the most elegant solution, but it appears that subclassing View is intended for alternate media (eg PDF), and I can't see how to direct Cake to use that class when manufacturing the view for a given controller's action.
Shove the function inline in the .ctp file. I'm not even sure if this will work correctly, and it seems ugly to put functions in a .ctp file.
Any advice?
Well, you're not explaining what kind of super complex logic you want to use there so I would say go for 3). It is very well possible, you can load helpers in a view files:
$this->loadHelper('MyFancyLogic');
You can also checkout view cells. But again, you're not explaining what problem exactly you try to solve it's hard to recommend anything specific. So I would say it's a helper or a view cell.

Should I call parent directive controller or create service

Let's say there is a "conversation" directive, made of "message" directives.
The message directive has a button to delete it.
The conversation controller has a method to remove a message from its list.
In Angular documentation, they say we can use "require" to access a parent controller from a directive controller.
And here, the answer suggests to use require too, and to create a service only if you can't use require because the 2 directives are not related.
Isn't it a bad practice to call a controller from another controller ?
I thought service was typically used to share information between controllers.
Don't you think it would be better to create a service with the deleteMessage method, and inject this service in the message controller ?
I'm personally not a fan of calling a function on the parent or root or stuff like that, as its coupled in a kind of implicit way. I prefer to use a service as you mentioned or injecting the concrete function(s) into your directive.
Below are some pros and cons for both approaches. Please note they are based on my personal experience (and I'm not an expert).
Services
Services are singletons, meaning there is only one instance in your whole application. This can have several advantages, if you need them:
it's always there (you don't need to create it explicitly)
it can cache data which can be usefull, e.g. to maintain the state of a view/page
it can be used to exchange data between different components
it can easily be injected where ever you need it
This can also lead to some disadvantages though:
if different components share the same service, they might mess up each others data
components (i.e. directives) will depend on that service, leaving the user of the directive no flexibility in how he wants to use that directive (e.g. what should happen when a user clicks a button). Meaning that basically the concrete functionality is "hard-coded" in to the directive.
I personally like to use services, if they have a direct link to the directive (and to nothing else) or do not store any state, for example if they only contain simple helper functions.
If in your application you have one conversation list, then I would consider implementing that in a service that exposes functions like addMessage, deleteMessage, sortBy, etc.. Then it can be injected in to any component which needs access to that (central) list.
Passing functions as arguments
On the other hand, if you have a message-directive, you might want to use it for other kind of messages as well..? That is messages which are not from the conversation but maybe from a mailbox (just a stupid example ;)). Then I wouldn't couple the service and the directive. You could inject the deleteMessage-function, which in one case would remove it from the conversation and in the other case remove it from the mailbox.
I think both approaches are valid, but always depend on the scenario and how the components are shared/reused over your application.
The second approach might be nicer from a "coupling"-perspective, but might get complicated in case of lots of parameters and when passing parameters over several levels of components (e.g. to child-child-child directives).
The first approach is easy to implment and can have several advantages, but results in the component being directly coupled to that service, lowering its reusability.
Do you really need to put the delete button in the message directive ?
Since the delete button is to suppress the message from the conversation controller list, I'd rather put the button in the conversation view.
That being said, if you really want to have the delete button on the messagedirective, I would simply pass the delete method as an argument in your directive. When doing this you don't have to worry about which controller defined the function, you simply call it from your child directive (and if you want the parent controller to execute it, simply pass a binded function to your directive).

Splitting functionality across controllers that must interact

We are using Angularjs and ui-router. We generally have a layout of each page that utilizes views. We have a filter view, sort view, and pagination view; as well as display views that can be swapped in and out.
Logically when changes are made we need to any of theses controllers we need to update the displayData as appropriate. Changes to filter should run the filterMethod, but also need to run sort and then pagination logic afterwards, while changes to sort should run just pagination after, making a clear order of operations for when each controller needs to it's update.
My problem comes when I consider that in some cases we may not want to utilize all 3 controllers. We may want filtering, but not pagination for example.
We are having trouble finding a clean way to make these controllers 'just work', so that we can plug in whichever control we want in uirouter and have them function. The problem is mostly one of scoping. If I do the obvious thing, and have each controller define their own updateData method when changes are made to it, I run into scoping problems if I want them call the next controller's update afterwords. The filter controller can't call sort because the two controllers don't share a scope. I can use broadcasts, but what if I want a filter and a pagination controller, but not a sort? How do I ensure that sort runs before pagination if both are present, but if sort controller doesn't exist pagination knows to run after filter?
I could instead move everything up to my top level controller, and then things just work. However then I end up with a controller that feels like it's doing way to much, It's cleaner to have one controller for each type of control if possible.
We have other approaches we could use, but they feel like their making pretty strong presumptions about our controller scheme. If I later added some fourth controller I would have to modify everything because each controller is really hard coded very explicitly with presumptions about how the other's run.
This seems like a common issue. Is there a a best practice or convenient technology for handling splitting of functionality across controllers?
Hoist the data, not the display logic. There are only two ways to share data between controllers cleanly: a service, and a parent controller.
If what you were sharing was data (eg: displayData), I might suggest a service object, but sounds more like application state (eg: orderBy), so I think these "settings" should live on a parent controller.

Data logic on load using a component - cakePHP

I have a project I'm developing which includes articles that can be commented on (comments stored in separate table of course). I want to perform pre logic on a field from each comment, wherever they are loaded through-out the app. The data logic I want to performed is from a custom written component.
The logical place to me that this could be achieved globally is from the comment model, but I could be wrong.
I'm not even 100% if I can use a component from a model, but I've been trying to do this logic using the afterFind() call-back function:
function afterFind($results) {
foreach ($results as $key => $val) {
if (isset($val['Comment']['created'])) {
$results[$key]['Comment']['created'] = $this->Dateconvert->howLongAgo($val['Comment']['created']);;
}
}
return $results;
}
I have tried echoing from inside this function and it doesn't actually seem to be getting called but searching hasn't revealed any functions that do, but I believe afterFind() is best to illustrate what I'm trying to achieve.
So I am looking for a solution where I can performed the post-load logic on articles comments, whether they are being loaded from other controllers with associations to comments or in the comments controller. Basically a global one hit solution :D
cakephp indicates that components are for controllers and behaviours for models and helpers for view...
knowing that first, you may also know that you can use any part of it wherever you want because cake still php, though is not recomended... if is a library of functions you may want to put it inside the libs folders and access it from there.
how, easy use App::import('component', 'nameComponent'); component can be lib, controller, etc..
Having said that, afterFind is a good place to do after load things, remember that this function is call ONLY when a find is used, if you use, any other like query or save or update it won't be called.
hope this helps you :)

Loading CakePHP Helpers

This is a multi part question.
Background:
I'm building my first site using CakePHP, and I like it so far. I've got a DB setup, initial data loaded, and a few models, views, and controllers to interface with the data.
I've created a globally accessible function to create Add/Edit/Delete type image links in various areas. It will be used across multiple views, so I need it accessible, essentially, everywhere. The function is defined in /app/config/bootstrap.php. I was hoping to use the HTML Helper's $html->image() and $html->link() methods to facilitate this, but they're not available in bootstrap.php and I'm not sure how to load/access the HTML Helper where I've defined my function.
Questions:
1) Is this a reasonable/idiomatic place to define a function of this sort?
2) If this isn't the correct place to define the function, where should I define it?
3) If this is the correct place to define the function, how can I go about loading various CakePHP helpers?
Again, I am new to CakePHP, so please let me know if my question is unclear, and forgive my ignorance. I've read/searched through a fair amount of the CakePHP documentation and while I can find plenty of references to loading helpers within Controllers via App::import(...); or $helpers = array(...);, I do not seem to have access to the App object and the $helpers member is specific to the AppController class, I assume. I assume I'm going about this incorrectly, so please help me understand the Cake way of accomplishing this.
No, that is not the correct place for such a function (or more accurately, it goes against the MVC paradigm). A better approach would be to create your own helper for the function. Depending on the complexity of the links you could also use elements.
As a rule of thumb only functions that are completely independent of anything else in the app should be in bootstrap.php, and even most of those would often be better somewhere else.

Resources