Kohana beginner question: controllers, hooks and vars - Oh my! - php

I'm new to the MVC concept, and somewhat new to PHP.
Question 1
Before every controller is loaded, I’d like to run a function which checks to see if a database-table exists. Is the proper way to do that with hooks?
Question 2
Before every controller is loaded, I’d like to set a few variables which are determined by a call to the db. How/where is that supposed to be done in a MVC (Kohana) setup?
Edit: Regarding Kohana v2.3.4

For Question 1 & 2, I would use hooks for these. Hooks allow you to have code executed at various times throughout the framework's startup and tear down phases. Checkout the documentation page on hooks on Kohana's site. The events documentation has all the events listed that you can use throughout the framework.
Question 3: You don't ever really have to use a constructor in your controllers. One reason to do it may be if you have several actions that need the same object instances and things like that, you can create them once in the constructor.

Related

How can I populate Zend_Layout variables with backend data?

When trying to adhere to established best practices like avoiding singletons, registry, static properties and base controllers, how I can populate my layout(and partials used by the layout) with data that is only used by the layout and common across all actions?
The typical scenario is menu which is built on variable data, like an database. Keeping separation of concerns in mind, the views/layout should never talk to an backend directly, but rather be told what to contain.
Using a front controller plugin is simply not possible without using the singleton "feature" in Zend_Layout. The plugin only knows the request and response object, neither has access to controllers, views or the layout.
Zend's action helpers have init/preDispatch/postDispatch methods. One can add action helpers to the HelperBroker (ex. using the bootstrap) and these will be executed in the normal application flow.
Using the init-method to inject data into the view is not possible since it's trigged before the controller/view is ready. preDispatch/postDispatch is possible, but not perfect, since these methods are always triggered when executing a controller action.
That means that all uses of the Zend_Controller_Action::_forward() will also execute the preDispatch/postDispatch in all action helpers. This doesn't have any big implications for the code except speed, I really do not want to be setting a view (or an view helper) variable several times. One can code around this issue using some sort of $firstRun variable, but I really don't want to track this in my own code.
Another method is doing this in the bootstrap, but in my opinion it really does not belong there.
So, how can I populate my layout/view helper with data from the database, doing it only once and still keep a good separation of concerns?
I've followed the ActionHelper approach, setting the view variables on the preDispatch method. It was the most logical place, in my opinion. In addition, my projects weren't using Zend_Controller_Action::_forward(), so I didn't have any speed concerns about multiple triggering of the helper.
Hope that helps,
You could go with Action Helpers as stated in this answer (take a look at the question too, its pretty much similar to yours)
I'd use action helpers too. Just fill the view variables and display them using plain PHP/partials/render/viewHelper (depending on complexity).
Your problem with multiple runs using preDispatch could be solved using
if (!($this->view->myVar)) { // or array_key_exist or isset - depending on your use case
$this->view->myVar = $someModel->getSomeData();
}
Which is just fine IMO.

Django development - how to lay out and use code properly

Hi i'm a PHP developer trying to convert to Django and im having a bit of a hard time understanding where to put things and how to use the new language. Basically what i want to know is for example in codeigniter i would make classes and functions in my controllers. Where do i do that in django?
I believe the 'view' in django is more like the controller in an MVC framework but all the examples i can find of the view are very simple and just call a template and pass it some data.
I currently have an index view and a 'rates' view in my current project. The index page will call rates via JS and pass it some GET variables. In my php version i used these to instantiate my rates class which when had all the needed functions in it. I want to do this in Django.
The reason that it is called, "MVT" instead of "MVC" is that "View" to Django means, "presentation of data (according to given logic)" and "Template" means, "display of data presented." In a traditional MVC paradigm, "Controller" means "executer of logic" and "View" is "presentation of the result of the executed logic". (They are almost the same idea, but not quite).
So, what does this mean? Basically, if I were building something in Symfony, I would put all of the logic in the sfAction components. In CodeIgniter, it would be in the CI_Controller. In Django, I will place all of the logic in the "Views".
Just like CI (and Zend and others) will then call a "View" from the Controller descendant, the Django view will also call a "Template" from its "View". (Symfony's views are often called in a different syntax, so I will leave that to the reader to research if so desired).
Looking at your example, it looks like you want to call a method in the "View" (which view is configured in urls.py) which simply instantiates another object which has "all of your logic in it". Something like:
def ratesHandler(request):
rate = MyRatesClass(request.GET)
return HttpResponse("Insert something here. ") #or render_to_response
The logic always belongs in the view. You can put whatever logic you like there - no need to put it into a class, unless you want to. If the logic is related to a specific model, though, it is best to make it a method of the model or the model's Manager.
In django: "models" go in models.py, "controllers" go in views.py and "views" go in templates.
Models tend to be classes that subclass django.db.models.Model
Controllers (in views.py) are often functions but you can use classes if you like.
Note that if you're just displaying data from the database you can often use generic views so you hardly have to do any coding at all.
I can't tell whether there is a question in the last 2 paragraphs of your post. If there is a question there, please edit your post so it's clear.

Beginner CodeIgniter concepts - Reusable view code, where to go? (Helper?)

I am a beginner with CodeIgniter still struggling to get a complete grasp on how to use the MVC ideology most cleanly.
I am writing a basic CMS system with the ability to vote on entries and follow people etc, consequently, I have found myself using the same or similar pieces of code across multiple views here and there consisting of various pieces of html and logic such as:
Voting panel
Follow/Unfollow panel
Login/Logout panel
Code to check if a user is logged in etc...
I am wondering where to put this code so it can be unified? I am thinking a helper is the way to go? If I declare the helper in the controller, it can be called from the corresponding view right?
Some of the elements are dynamic - such as a follow/unfollow button - It would need to check if you are already following the user or not and display the appropriate button, which would require a model to check. What I have now is that all the logic is in the controller and it returns an appropriate button, but it seems weird to be returning formed html code in a controller return as well. Should it be more like:
controller checks if you are following someone
the controller passes a boolean to the view
the view calls the helper with this value to draw the appropriate button
Also, as a secondary question, I have been doing a fair bit of looping through mysql arrays in foreach loops to process mysql results returned from the view. It seems like my views are getting somewhat complicated, but I can't think of another way to do it, although perhaps this should be done in another helper as well?
Apologies if this is a naive or repetitive question, there is indeed a lot of discussion surrounding this subject but it is not always easily relatable to another project.
Helpers are certainly one way to modularize anything that isn't DRY. Another is to use Partial Views. CodeIgniter looks like it supports partial views. Here's a good breakdown - not PHP specific but the discussion should be agnostic.
As far as handling user logins is concerned, you will probably want to use a static class and the singleton design pattern, which will allow you to check to see if a particular user is logged in or not anywhere in your application. There is a good tutorial here
http://www.phpandstuff.com/articles/codeigniter-doctrine-scratch-day-4-user-login
Loading the helper, I don't believe loading it in your controller will automatically load it in your view. I think you have to re load the helper in your view file, or you have to autoload the helper. (cant remember off top of head but Im pretty sure).
Regarding looping through the mysql results, you should be using a model for this, always. Any functions which are grabbing or sorting information from your applicaiton, should be done within the model. Then, in your view file you loop through the results and format the data how you choose to.
When developing http://newspapair.com which has the vote functionality you mentioned I used helpers and custom classes to spread the functionality across multiple views.
Helper - has functions without a class. So a standalone function or group of functions can be placed in a file and saved as a helper.
For instance I used a helper with generic form processing functions for NewsPapair, instead of a static class. But this is not the "best practices" thing to do. I did it this way because I already had the functions from a previous project.
As far a looping through MySQL results, try to write a query that allows the DB Server to do the heavy lifting. This will make your code more efficient. Perhaps ask a question about a specific query with example code. Plus do all of the data gathering in your Model.

Whats the difference between a front controller plugin and an action helper? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Zend Framework: Controller Plugins vs Action Helpers
I know what the difference is technically, and how to register a front controller plugin/action helper, but it would really help me if someone with more experience in zend framework could explain me the different use cases for the two (examples would be great).
I still have to learn a lot when working with zend framework and I guess it could make things more easy when I would know when to use an action helper rather then a front controller plugin and vice versa.
Thanks!
A front controller plugin executes for every request, at specific stages in the MVC cycle. You can use it to perform work like checking whether a user is authenticated or logging requests to a database for analytics.
A controller action helper can also perform at different stages of the MVC cycle, though this isn't mandatory. The key difference between plugins and action helpers is that your controllers can interact with action helpers to change their behaviour, or use some on-demand functionality.
A plugin is often better for things that ALWAYS need to happen, while an action helper is useful for occasional tasks, like sending a JSON response.
An example for controller/helper hooks:
You have an action helper that checks at preDispatch whether a user is logged in and, if not, asks the user to log in. In your login controller you want an exception to this rule, or you'll loop infinitely. In the login controller's init method you can do the following, as the init() is called BEFORE preDispatch:
public function init() {
$this->_helper->myHelper->setAuthenticationRequired(false);
}
This sets a boolean in the helper to skip the authentication check.
A great ressource is this UML diagram: http://www.kitpages.fr/cms/site/tutoriaux/sequence_globale.jpg
You can see the calls to Plugins and then Helpers, and the yellow zone being the dispatching loop.
Don't forget that Helpers hooks (#17 and #22) won't be triggered if the helper has not been called/used, this is great and could save you time as unused process won't need to be initialized.
I mostly use:
Plugins for heavy logic required project wide (as Authentification, Acl, ...),
and Helpers for most specific tasks closer to the action (like sorting, filtering, pagination, json encoding, pdf download) avoiding duplication of code in many actions

What is an alternitive for using action(); or forward(); in ZF for pulling out different controller/actions in the layout?

Basically in order to have a profile Block u need - let's say profile controller, PhotoController, may be dashboard to show at the same page at the same time and to reach this in the zend framework is sometimes done through helper action() or forward, are ther better options?
I'm not sure I understood your question clearly. But you should avoid the action helper because it decreases significantly the performance of your application.
"The Action View helper basically creates an additional
dispatch, copying the request object,
and creating a loop-within-a-loop .
The setting up of the dispatch process
is a costly one, anyone who has
profiled their code will have seen
just how much of the process of a Zend
Framework application this eats up.
Creating a whole extra dispatch must
be a bad idea, even the Zend Framework
Performance Guide notes this fact."
This quote is from this article that explains why you should avoid it and what are the alternatives, why I believe to be the purpose of your question.
Maybe action helper or controller plugin using this method:
if ($condition) {
$this->getRequest()
->setModuleName('mymodule')
->setContollerName('mycontroller')
->setActionName('myaction');
// ->setDispatched(false); // redirect
}
Or controller plugin changing layout, using suitable view helpers.

Categories