how do you trigger a MVC application.
im only used to use procedural coding. since everything are classes, how do i trigger the first method, where should this method be put, and what should the class holding this starter method be called?
thanks
This is too general of a question. The answer will be subjective, because it can be done in many different ways. Your best bet is to look at a simple, lightweight MVC framework, see how they did it, and use that as a guide. I recommend checking out LightVC.
Generally all requests are routed through an index.php file. The request url is inspected to figure out what class file to include. For example, a request to /users/login would fire up Users_Controller, and then it would execute the login() method on the Users_Controller class. This is how most frameworks do it, but like I said, you should look at their source to get a better feel.
MVC applications have routers which based on the URL will call the appropriate controller and function inside.
Take a look at the flowchart of CodeIgniter for example -
http://codeigniter.com/user_guide/overview/appflow.html
Remember an MVC application is like a website, so when the user visits a page in their browser, it will call the methods automatically associated with that page, in the Controller.
Related
Im building a little mvc style framework, with a single point of entry through the index in the public folder. I am now passing all my ajax requests through this, and directing them to the appropriate controllers in the private application directory.
What are the pros and cons of doing it like this?
should I do be doing it like this? or another way?
Initially probably not many cons. As Pickle pointed out you have everything in one area so easy to find.
I would say that functionality should stay in the controller where it belongs. Just because the input and output are AJAX shouldn't matter. In fact, you could have a method in a controller like a show user method that could either output an HTML page OR AJAX data. No reason to put that stuff in a separate AJAX controller when it belongs in the User controller.
Honestly this is all design decisions. It's just my preference to keep things where they belong logically and approach AJAX as an input and output problem and build your methods to handle that in/out.
We rolled our own framework and one thing we build was a router that handles incoming traffic. And ajax calls have a .json at the end. This is then available to the controllers and if a controller supports ajax requests it will output valid JSON data instead of passing the data off to the view and then displaying HTML.
Pros: You don't have to search through a bunch of code to find out where your AJAX request is being handled.
Cons: None I can think of.
The only potential downside would be any "expensive" bootstrapping going on that the AJAX doesn't need which may slow down response times. APC may help or negate this, though, depending on what you are doing, and you could probably tailor the bootstrap process to handle lightweight requests.
FWIW, the normal Drupal method for AJAX funnels everything through the same place as normal pages. This is also done to help provide a fallback when the user doesn't have JS enabled.
Just been looking at the way I am structuring my classes and wondering it there is a better way.
I have forms which pass the information through to the process class. This class just forwards everything onto my main class which then does the work. When the work is done, it then passes the information through to the database class to carry out the sql.
If in the main class there is an error, the error goes back to the process class. The process class sets a session variable true is the error is there.
It then goes to the referrer which is the original page and on that page I have code which leaves an error message if the session variable is present.
I know this possibly isn't the best way to explain things, but does it sound like a reasonable way to do things?
I am just trying to improve the way I write classes!
Thanks
The workflow you describe somewhat reminds MVC but it probably isn't. If you are interested in making the internal architecture of your application more structured and easier to understand then here's something to read and experiment with:
Model-View-Controller
The Model-View-Controller (MVC) Design Pattern for PHP
Model View Controller MVC tutorial
I'm new to Zend Framework MVC. I love a lot of things about working with an MVC environment, but find myself confused about it structurally sometimes.
I have a simple task, I'd like to flag certain users on our site to track their movements. For this I've set up a simple table in the database, and started to code in my _initTracking() function into the bootstrap. I then realized I was approaching this from the wrong direction - I'd like this to be one of the last functions that fires, to avoid mucking up my tracking entries with header redirects, and to ensure all autoloaded classes are present. How do I do this? Is there an "onBeforeRender" type of function? If there is I couldn't find it.
Thanks
I would suggest using a ZF plugin. You could track user's actions in plugin's postDispatch() or dispatchLoopShutdown() method, depending on how granular your tracking needs to be.
Some reading about ZF plugins - http://framework.zend.com/manual/en/zend.controller.plugins.html
Also a really neat article about request lifecycle in Zend Framework - http://www.eschrade.com/page/zend-framework-request-lifecycle-4b9a4288.
Ended up putting this in the layout scripts. There's probably a better way of doing this, but in my case (having all views I wanted the code to run in under 2 layouts) it was the easiest, and accomplished my goal.
I think the best place for this would be in a postDispatch() hook in your controller.
Have a look at http://framework.zend.com/manual/en/zend.controller.action.html, specifically the section on Pre- and Post-Dispatch Hooks.
This would suit placing your tracking code in a base controller - which your action controllers would extend, keeping the tracking code in one location.
Greetings all!
Looking for some help with MVC in a PHP context. Currently I am building a small, lightweight MVC framework to help expedite application development at work. It's a long hard separation eliminating inline code - at least with numerous projects looming overhead and the temptation to utilize it ever-present.
I understand most of the basic requirements of MVC, and I've already begun porting some of my existing classes that are in Singleton pattern over as utilities in my new framework (these are mostly basic 'handlers' to perform site services - a class for file uploads, authorization, wrapped PDO database queries, error printing etc.)
What I can't seem to grasp moving forward after reading much documentation is the best approach to instantiating views. In my old, inefficient design I would switch off a $_GET variable to switch ouput from within the home view. Just going off intuition, this seems like an extremely bad way of getting the job done.
I've looking into CodeIgniter, and it would seem that there are predefined functions for loading views within that framework. What is the best approach to such an application design? Would it be a class based 'link factory' that utilizes the same variables to fetch content, select the proper view file, and place it in the page flow? Also, how could the new view be included between the header and footer includes in the root index without using switches? This is the only thing really confusing me - I really hope I have worded myself clearly enough.
Thanks all as ever!
I highly recommend "PHP Objects, Patterns, and Practice" by Matt Zandstra. A good bit of the book deals with creating MVC frameworks and would be very, very helpful to you.
It covers these patterns (which you can also research elsewhere):
Front Controller
Application Controller
Page Controller
Template View
View Helper
While I'd suggest going with an established, flexible framework (like Zend), to answer your question, here are the steps involved as I see them (understand I stopped trying to write this kind of stuff a while ago, this is based on my understanding of the existing frameworks I've used).
Some kind of router parses the request and translates to a controller object with an action (or takes the default) and optional parameters. The router then calls the controller object's function matching the action.
The controller object (usually extended from a generic controller object) process the request and determines what data to pass to the view, as well as what view to use. Most frameworks setup a default view based on the action, but ultimately it's up to the controller to decided what view to use.
The view takes the data and displays it.
That is my very simplified take on the process.
In the last couple of websites I made, I implemented a kind of MVC-style controller, I think.
I used mod_rewrite to send everything through index.php, so the url became a querystring.
It worked, but I'm wondering if it's a bit hacky, or just the accepted way of doing things. Is there a better way? I don't want a framework, I want to learn to do it myself.
Try my smallest framework in the world.
<?php
$g=$_GET;$c=#$g['c']?$g['c']:'Home';
if(!#include"c/$c.php")die('fail');
$m=method_exists($c,$m=#$g['m'])?$m:'index';
$o=new$c();$o->$m($g);
That goes in index.php and your controlls are Blog.php in ./c/Blog.php.
class Blog {
function index()
{
echo "Hello world";
}
function otherpage()
{
echo "ZOMG!";
}
Made mainly as a joke, as I wanted to make a framework that could fit in a tweet, but the basic logic is there ;-)
Passing everything through a single point of entry, e.g. index.php is not MVC, it is the FrontController Pattern. This goes well with MVC though. See my related answer here.
Apart from that, why not check out some of the frameworks around to learn how they do it. Doesn't mean you have to use them, just look at their code and adapt for your own framework.
That's the way I accomplished it. I then created a dispatch table that new, based on URL, which controller to instantiate and which dispatch to run.
How about learning to do it yourself, but still use a framework ? Either way, take a look at an open source framework like Symfony or CMS apps like Wordpress, Jommla! etc, and you will find that they all use mod_rewrite to set things off.
Most PHP frameworks make use of mod_rewrite do accomplish the same objective, and it's the only way to suppress index.php and make the urls more friendly, in a segmented way.
I'd say you're in the right path.
That method you used is called FrontController Pattern, and it's used by those frameworks as well, to go along with the MVC pattern.
If you care for a suggestion, I'd recommend you to make every request pass through each page controller, extending a base controller, since every site has some base data structures that you will probably need to use in every page, such as templates and session control.