Jump to content

MVC, is this alright ?


svu666

Recommended Posts

Hello,

 

I'm pretty new to PHP and programming in general.

I don't have a lot of experience at all.

 

Something I'm wondering about a lot is that even if my code works I still don't have the certainty that I've coded it in a right way without making big mistakes which will sooner or later be the cause of problems and lots of frustration.

 

I know that a feeling for these things will probably develop more and more in time but I can't help asking experts opinions

about these kind of things.

 

I've been trying to write some code following a model view controller pattern to learn how it operates and learn more what it's all about.

I'm aware that the code probably doesn't include sufficient checks on inputvalues or security of the queries etc.

I'm just testing out the structure / principles of MVC.

 

All kind of remarks are welcome though.

 

 

I've made a small code example that will display a default of 3 tables (3 different views) with the same values but different formatting.

 

They will each display a list of books.

 

(in a Table with borders , a Table without borders, A Table with borders and some links next to each row)

 

The links next to the third table will make it possible for a user to go to a Book detail view and to go to a Book edit view.

 

The code starts at : index.php

 

In index.php a new controller object will be created and it runs its "start()" method. (controller.php)

 

The start() method in the controller will check for and catch all the possible actions that are happening.

 

For example if bookid=1 and action=showdetail in the URL the controller will catch this and run the corresponding code to display the detail view of a book with id 1.

 

After catching the right parameters the controller asks the data from the right model function and transfers it to the right

view template.

 

Actions that happen on a view template (for example some kind of "save") will again send parameters to the INDEX.PHP (for example bookid=1 and action=editsave).

 

Here the controller's start() method will again catch the right parameters to continue with the corresponding actions using

the right model and view.

 

1.

I was wondering if it's OK to send all the parameters back to index.php wich creates the controller that will handle the right combination of parameters.

Does it really recreate the controller everytime it runs or does is somehow reuse an existing controller if there is one ?

 

2.

I first tried to send the paremeters to the controller.php directly but this didn't work so I figured out I had to send it back to index.php which starts the controller's start() method over again.

Is it ok to send everything back to index.php or did I somehow do something strange here ? (Just wondering because it seems strange that every action runs code to recreate the controller object).

 

3.

Is it ok to do all the handling of all possible scenario's in the controller's start() method ?

 

4.

In my default view I'm using 3 different tables that are all represented in their own .php view file.

Is there a way I can reuse the "query result" that will be used for all these 3 views since it's the same ?

 

At this time the controller demands the same action on the model before calling each view because they will display the same data then this data is transferred to the view.

In the views themselves a while loop is used to fetch all the rows from the query result.

 

I can't reuse the query result for each view because after the first view it seems like the query result is on it's end. (through the complete while loop).

Can you somehow reinitialize this one query result or is the right way to do it the one I used ... having a query for each view even if they generate exactly the same data.

 

5.

Are there other things I should be aware of or other stuff I should implement ?

 

I can post all the code if this might be helpful.

I've already tried to get some help on some other forums without too much success...

 

Thanks a lot for your time and help!

Link to comment
Share on other sites

As you say you're new to PHP and programming in general, I'd suggest to try an already established framework. There are so many out there you can chose, starting from microframeworks like Slim and to big ones like ZF2, Symfony or Yii. Somewhere in-between you'll find CodeIgniter, Laravel or FuelPHP. It is a good idea to understand how a framework works before thinking of rolling your own; even if it's a simple one.

 

I'll try answering your questions.

 

First of all, you'll need a router that is responsible for mapping URIs to controllers and controller actions. Basically, it will get the URI, explode it into pieces and check if a controller and action exist.

 

Let's assume you have this URI:

site.com/index.php/users/ - which can be rewritten (mod_rewrite) to - site.com/users/

 

The first piece of the URI can be treated as a controller, so the Router knows that it should find controllers/users.php. If no second piece if set, it will call the "action_index" method.

 

Now the URI becomes:

site.com/users/add/

 

The second piece is treated as the controller action and the Router knows that it should find a method (action_add) inside the Users controller. In this way, you can create CRUD operations easily and organize them logically.

 

To answer your question number 1 (and 2 I guess), yes, it is normal for everything to pass into index.php as it is the only access point into the application. However, that file shouldn't contain any logic on how things are done; it just does basic includes and runs any class that should be initialized (like the router). Try separating concerns as much as possible.

 

Question number 3 is answered above. You shouldn't give all responsibilities to start() or any other, single method for that matter. A controller can do a lot of things and doing all of that in a single method is overkill. Adding users should belong to users/add. Deleting to users/delete and so on.

 

Question number 4 is a typical MVC one, because people forget what Models are for. You can easily reuse queries by writing them inside your models. Any controller that needs some certain data, can take them from the model. Don't write SQL code more than once because it'll become a pain to maintain (no rhyme intended). Anyway, you will need to pass the query results (fetched array) to the view each time you use it. Views aren't supposed to read directly from models; it is the controller who passes variables to it, query results included.

 

As I mentioned in the beginning, you should get some knowledge from other frameworks, on object oriented principles, design patterns and so on. You need those information not just to create a framework, but to get a better understanding of how applications can be created. It's quite difficult for someone to give you all the information you need to create a framework because it's too much for a simple forum post.

Link to comment
Share on other sites

Well,

 

Sorry for these long posts. It's often hard to explain what's going on and might be annoying to read.

 

I've been dabbling a bit in Joomla to create some simple/custom components.

While my final solutions works I still have many questions.

I had to follow the Joomla MVC way of doing things to make this happen.

 

While using the Joomla framework I've never really grasped the "whole" or "basics" of MVC itself.

It was always "tainted" with a lot of Joomla stuff.

You really need to learn how Joomla implements MVC in order to truely understand the whole and I'm not there yet (by far).

 

Since this was never 100% clear and because even the "simple" Joomla "hello world" tutorial :

 

http://docs.joomla.org/Developing_a_Model-View-Controller_(MVC)_Component_for_Joomla!2.5

 

Is not really that simple to completely grasp I thought of just trying to build my own very very simple MVC app, just to figure the basics out some more and make the basic working principles of MVC a bit clearer.

 

Of course my little experiment will be a lot more basic and less "clean" or correct.

It was just my way of learning and understanding it more using a real world , yet simplified , example.

 

I suppose I often need to DO something completely myself to really "grasp" the basics.

 

I agree that at this time using an established framework would be a lot better suited for production applications etc.

But getting into one or deciding a good one to use and really understanding the basics keeps my head spinning. Again that's why I just tested this stuff "on my own" first.

 

Often a lot of the clean and beautiful implementations (like in Joomla) make it not always as easy to learn.

It seems as thought the complete basics are hidden in all these nice and clean layers, wrappers for everything.

 

Give me a crude ,unsecure , ugly and basic example , that seems to work for me best :)

 

***

 

A few more questions...

Is it always advisable to use a clean URI ?

(ripped the next example from wikipedia)

 

At this time I'm using something like :

 

http://example.com/products?category=2&pid=25

 

instead of

 

http://example.com/products/2/25

 

Is there a huge advantage in using the clean URI and should one make a priority of implementing something like this ?

 

***

 

Thanks for confirming that it's normal to pass everything to index.php. I also came to this conclusion, just wanted to verify if that it's ok.

It seemed a bit strange that every time I pass parameters to index.php the controller object will be created again.

Will it truely be recreated or will it in fact be reused if it somehow already exists because of previous operations ?

 

***

 

The start() method of my controller will always run after going to index.php.

In the start() method it will be determined what will be the right functions to call depending on the parameters that are being transferred to the index.php. Maybe I mixed the "router" and "controller" a little bit here.

 

It seems like my controller :

 

1. "routes" the code to it's right part

2. Runs the right code (make calls to the model , transfers returning data to the correct view)

 

***

 

My queries indeed exists only in the model.

But somehow for every seperate view that wants to use a query result I am calling this query result again via the controller using the models function.

 

I'm not sure if it's possible to use one query result throughout more than 1 view .

 

So my query itself is indeed reused in more than one view (it exists only in the model) and so a few different views rely on the same model function to get the data. But the query result data itself is never shared and needs to be "demanded" again for each view even though it is in fact the exact same result data.

 

My controller does this kind of transferring :

 

1. controller demands the model to run the function that returns the correct data

2. controller transfers this data to the view.

 

If my 3 default views are shown , using the same data , they all have their own instance of resulting query data.

 

Is that the/a right way of doing it ?

 

*-*-*-*-*-*-*-*

 

I think I'll look into some of the (simple) frameworks to see some more implementations of MVC.

But I just wanted to get some feedback on my own stuff to see how far my way of doing things is correct and where it needs some adjustments :)

 

I can always post some code examples if that can make things easier to understand.

 

Thanks again for your reply. It's really really appreciated a lot!

 

Link to comment
Share on other sites

I'm afraid you'll need to read some more information as most probably the concepts that make a MVC application are yet confusing. Anyway, I'll try to answer your questions again.

 

Clean URIs and Routing

As the Router maps URI pieces to controllers and controller methods (which I like to call "actions"), they're quite linked with each other. They work well together by having a defined format for the URI that can be parsed and transformed into pieces. If you create an URI with multiple GET parameters, there's no good and automated way of mapping it.

 

A normal URI that goes well with the Router is:

index.php/products/show/25/

 

It's widely used because the index.php part isn't that bad, even if the user can't rewrite the URI. With rewriting, "index.php" can be removed and the URI becomes a little nicer. As you can see, the complete URI is just a string which can be exploded by "/" and turned into an array. From that, the Router can read each piece and determine what to do:

 

/products/ => The router will search for a controller class named "products".

/show/ => The router will search for a "show" method of the "products" controller. If this wasn't set, index() or start() or whatever would be called.

/25/ => Is a parameter that the Router doesn't care for. It can be retrieved by a URI helper that fetches URI segments.

 

That's the very basic idea of how a Router works with clean (I would call them SEF - Search Engine Friendly) URIs. A lot more can be done to add features to Routing, but the main concept is that.

 

Recreation of controller objects and Views that share data

On a typical MVC application, only one controller is called per instance. From the previous example, /products/show/ will only run the "products" controller. When the users goes to /orders/, yet again only the "orders" controller will be called. So, there's no controller recreation when you call once a single one.

 

It's almost true for views too, but those can have included files or inheritance in some template engines. However, the idea is pretty much the same as with controllers. The "products" controller will open the "products" view, send parameters to it (query results included) and finally render it.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.