Twitter
Fri
25
Apr
'08
PDF
Print
Send
 
Hits (31856) | Comments (30) | Favorited (0) | Votes (0)

What Is MVC

Revised for Joomla 1.5 beta 2

Model-view-controller (MVC) is an architectural pattern used in software engineering. In complex computer applications that present lots of data to the user, one often wishes to separate data (model) and user interface (view) concerns, so that changes to the user interface do not impact the data handling, and that the data can be reorganized without changing the user interface. The model-view-controller solves this problem by decoupling data access and business logic from data presentation and user interaction, by introducing an intermediate component: the controller. It is common to split an application into separate layers: presentation (UI), domain, and data access. In MVC the presentation layer is further separated into view and controller. MVC encompasses more of the architecture of an application than is typical for a design pattern.

Model The domain-specific representation of the information on which the application operates. In Joomla it is MySQL database tables. Joomla model classes basically contains table schemes. Formerly known as mosTable.

View Renders the model into a form suitable for interaction, typically a user interface element. In Joomla it is set of View class and 1 or more templates.

Controller Processes and responds to events, typically user actions, and may invoke changes on the model. In Joomla process tasks. to trigger tasks, Every thing you need is to create methods in controller class with the same name as a task.

Joomla MVC Works as follows

  1. User access Component (without any task or controller variables)
  2. Default Controller Class constructed. Then controller call default view and displayed. Of course this controller render default view.
  3. User click on any control. The control should have task and controller variables in URL, or only task. (E.g. index.php?option=com_mvc&controller=books&task=view)
  4. If controller passed Joomla looks for new controller file and construct it. Then Render according the task.

Where is the Model? Model is used inside controllers' task functions. If it is for example Publish task, function publish will launch appropriate model to change published field.

File structure explanation

  • Component
    • Controllers
      • Controller1.php
      • Controller2.php
    • Views
      • View1
        • Tmpl
          • View1.php
          • View2.php
        • View.html.php
      • View2
        • Tmpl
          • View1.php
          • View2.php
        • View.html.php
    • Models
      • Model1.php
      • Model2.php
    • Admin.component.php
    • Controller.php

Controller folder contains controller classes. Foe example for Book Library, Book Category controller, Book controller, Book Publisher controller and so on.

Models contain Model classes. One Model class is equal to one DB table.

View folder contains view classes and templates. Every view class may have few templates that are stored in tmpl folder. Every view class has the same name view.html.php. And tmpl folder contains html template files. Admin.component.php is a component launch file and controller.php is default controller. Let's create most simple MVC Component.

We will create component called mvc.

The component we will create can be downloaded here.
  1. Create folder administrator/components/com_mvc.
  2. Create file administrator/components/com_mvc/admin.mvc.php. This is standard Joomla file that will be launched on access to the component.

    File listing: admin.mvc.php

    1. <?php
    2. defined( '_JEXEC' ) or die( 'Restricted access' );
    3. require_once (JPATH_COMPONENT.DS.'controller.php');
    4. if($controller = JRequest::getVar('controller')) {
    5. require_once (JPATH_COMPONENT.DS.'controllers'.
    6. DS.$controller.'.php');
    7. }
    8. $classname = 'MvcController'.ucfirst($controller);
    9. $controller = new $classname( );
    10. $controller->execute( JRequest::getVar('task'));
    11. $controller->redirect();
    12. ?>

    Line 2 is to protect document from direct access. line 4 to require default controller. This controller will render pages if controller GET/POST variable is not set. 6-8 to include other controller class if controller GET/POST variable was set. 10-11 create new controller class. 13-14 execute controller or render page according task

    This file is quite simple. First it includes controller, then create class, then execute.

  3. Create administrator/components/com_mvc/controller.php. This is controller we includes in line 4 of admin.mvc.php. This controller will be launched if there was not any GET/POST controller variable found.

    File listing: controller.php

    1. <?php
    2. jimport('joomla.application.component.controller');
    3. class MvcController extends JController
    4. {
    5. function display() {
    6. parent::display();
    7. }
    8. }
    9. ?>

    2d line to include Joomla API controller class for extending new one created in line 4. Function display render default view. More about that later.

    Basically that is all we need. If instead parent::display(); we put echo "test this"; we will see this on the main page of the component. But let's create fully structured MVC component. For that we need to create View for this controller.

    Default view should have the same name as the component.

  4. Create folder administrator/components/com_mvc/views.
  5. Create folder administrator/components/com_mvc/views/mvc. To create default view we need to name this folder as we named component.
  6. Create file administrator/components/com_mvc/view/mvc/view.html.php. This file will have view class. We do not use "mvc" word in the name of this file. Every view class has different folder but the same file name. it is view.html.php

    File listing: views/mvc/view.html.php

    1. <?php
    2. jimport( 'joomla.application.component.view');
    3. class MvcViewMvc extends JView
    4. {
    5. function display($tpl = null)
    6. {
    7. JToolBarHelper::title(JText::_( 'MVC Main' ), 'generic.png');
    8. parent::display($tpl);
    9. }
    10. }
    11. ?>

    Line 2 we include Joomla API View class to extend new one we create in line 3. 5-10 create function display(). This function is called by default, by MvcController class if not task called.

    I used JToolBarHelper::title() to display tile. Here you can also use other JToolBarHelper methods. Also here you can make DB queries and prepare HTML elements to render such as Published Yes/No radio button set, Public/Registered/Special access select list, pageNav class to create navigation and other. Please, note the difference. In this view class we use Models(tables) and SQL queries to get information to create HTML elements to render. But in controller we make SQL queries and use models to control and operate records. Something like delete, publish, save, ...

    Function display() will be called by default if there is no GET/POST task variable set. parent::display($tpl); will call default template if POST/GET layout variable is not set. So let's create default template.

  7. Create file administrator/components/com_mvc/view/mvc/tmpl/default.php.

    File listing: views/mvc/tmpl/default.php

    <h1>MVC Main</h1>;
    <a href="index.php?option=com_mvc&amp;controller=list">List something</a>;

    This is HTML document. This template will display H1 header and link to other controller. This is complete MVC minimum component. We only lack Models.

    Please, save all files and try to call your new component. Login to Joomla admin and put to address line /index.php?option=com_mvc. Before you continue please, be sure all code works fine till this point.

    Everything you will read below just to explain some more things. How to control different tasks and different Views within one Controller. For that, let's create another section that will be controlled by Controller list. First link to controller is without task so we will call default View again and create some more links with tasks to call other Views.

  8. Lets imagine we clicked on index.php?option=com_mvc&controller=list link. That means we enable following lines in admin.mvc.php.

    File listing: views/mvc/tmpl/default.php

    1. if($controller = JRequest::getVar('controller')) {
    2. require_once (JPATH_COMPONENT.DS.'controllers'.
    3. DS.$controller.'.php');
    4. }

    That means we need to create file administrator/components/com_mvc/controllers/list.php.

  9. Create it.

    File listing: controllers/list.php

    1. <?php
    2. jimport('joomla.application.component.controller');
    3. class MvcControllerList extends JController
    4. {
    5. function __construct()
    6. {
    7. parent::__construct();
    8. }
    9. function display() {
    10. JRequest::setVar('view', 'list');
    11. parent::display();
    12. }
    13. }
    14. ?>

    JRequest::setVar('view', 'list'); tells this controller to look for View in views/list folder. If we skip or delete this line, this controller class will look for View in views/mvc default folder. So if we told controller to look for View in list folder, let's create it.

  10. Create folder administrator/components/com_mvc/view/list
  11. Create folder administrator/components/com_mvc/view/list/tmpl
  12. Create file administrator/components/com_mvc/view/list/view.html.php

    File listing: views/list/view.html.php

    1. <?php
    2. jimport( 'joomla.application.component.view');
    3. class MvcViewList extends JView
    4. {
    5. function display($tpl = null)
    6. {
    7. JToolBarHelper::title(JText::_( 'List' ), 'generic.png' );
    8. parent::display($tpl);
    9. }
    10. }
    11. ?>

    I won't explain this file. It is the same as views/mvc/view.html.php, only name of the class is different.

  13. Create file administrator/components/com_mvc/view/list/tmpl/default.php

    File listing: views/list/tmpl/default.php

    1. <h1>This is Default.php</h1>
    2. <P>This file launch automatically is nothing
    3. passed to JRequest::setVar('layout', 'something');</P>
    4. <a href="index.php?option=com_mvc&amp;controller=list&amp;task=test">
    5. test</a><BR>
    6. <a href="index.php?option=com_mvc&amp;controller=list&amp;task=new_task">
    7. new_task</a><BR>
  14. That is it. It should work ok now. I mean you can easily navigate from MVC component homepage to list controller homepage.

    But this file will display few links that have different tasks within same Controller. Here is how you can handle them. Start with task=new_task.

  15. Create function new_task in File controllers/list.php.

    File listing after adding function: controllers/list.php

    1. <?php
    2. jimport('joomla.application.component.controller');
    3. class MvcControllerList extends JController
    4. {
    5. function __construct()
    6. {
    7. parent::__construct();
    8. }
    9. function display() {
    10. JRequest::setVar('view', 'list');
    11. parent::display();
    12. }
    13. function new_task()
    14. {
    15. JRequest::setVar('view', 'list');
    16. JRequest::setVar('layout','newtask');
    17. parent::display();
    18. }
    19. }
    20. ?>

    We created function new_task() in line 13-18, that will be called if GET/POST task variable equal to new_task. JRequest::setVar('view', 'list'); tells controller to look for View in views/list/ folder. JRequest::setVar('layout','newtask'); tells controller that View should display newtask template or really newtask.php. Let's create it.

  16. Create file administrator/components/com_mvc/view/list/tmpl/newtask.php

    File listing: views/list/tmpl/newtask.php

    1. <h1>This is new task</h1>
    2. <P>This task1, task2, new_task triger the same function </P>
    3. <a href="index.php?option=com_mvc&amp;controller=list">Go back</a>

    This file displays some text and link back to list controller homepage. Save all files and try it. Try to navigate to list controller homepage and click on new_task link. If you see text of above listing you are done. Congratulation. You have just created new task.

  17. One more thins to know. It is possible to call same method with different tasks. For that add $this->registerTask( 'test' , 'new_task' ); to construct method of controllers/list.php.

    Final listing: controllers/list.php

    1. <?php
    2. jimport('joomla.application.component.controller');
    3. class MvcControllerList extends JController
    4. {
    5. function __construct()
    6. {
    7. parent::__construct();
    8. $this->registerTask( 'test' , 'new_task' );
    9. }
    10. function display() {
    11. JRequest::setVar('view', 'list');
    12. parent::display();
    13. }
    14. function new_task()
    15. {
    16. JRequest::setVar('view', 'list');
    17. JRequest::setVar('layout','newtask');
    18. parent::display();
    19. }
    20. }
    21. ?>
    Save all files and now try click test link on list controller homepage.
  18. Later I'll write a lesson on how to use Models and we will create simple guestbook component.

Comments
roedAvatar
Quote
- -
Written by roed VIP on 25 June 2008

Very cool !!!!!

I would really like to know how to make a guestbook as you mention. Have you any idea on when this tutorial will be ready?

Thanx for a great lesson :)

Michael 

-
avatar
Quote
- -
Written by Luis Noel Salazar on 28 October 2008

Hola, me parece muy bueno el tutorial del MVC, pero quisiera ir un poco mas allá, quizás si puedan publicar para almecenar datos capturados en un formulario, ademas no veo trabajando el modelo por ningún lado...

 

cualquier ayuda por favor!!! graciaas!!! 

-
avatar
Quote
- -
Written by Dau Thanh Hai on 03 December 2008

Very nice tutorial.

Is there one mistake right under 8 section:

File listing: views/mvc/tmpl/default.php

should be 

File listing: admin.mvc.php

?

-
avatar
Quote
- -
Written by thientran on 18 January 2009

thanks for your useful entry

-
avatar
Quote
- -
Written by saami on 21 January 2009

Thanks for this greate tutorials

-
avatar
Quote
- -
Written by sun on 30 January 2009

very sexy article

-
avatar
Quote
- -
Written by staricata on 17 March 2009

After this helpful, understandable explanation i belief that i'm not very stuped:)

Thanks:)

-
avatar
Quote
- -
Written by Ricardo Lima Caratti on 22 March 2009

Did you continue this tutorial?

Where is the model part?

 

 

 

 

 

 

-
avatar
Quote
- -
Written by neoo on 11 April 2009

I am waiting for the next one

-
avatar
Quote
- -
Written by fretful on 18 April 2009

 It really helped me understanding the mvc concept!

-
avatar
Quote
- -
Written by Ershad on 20 May 2009

Reallly Helpful

-
avatar
Quote
- -
Written by Andre Shank on 09 June 2009

There isn't much out there... this is one of the best simple ones.

 Congrats.

 AS

-
avatar
Quote
- -
Written by Mitesh on 15 June 2009

That a nice tutorial. Thanks. But can you help on creating a component outside and then importing it through the web interface provided under Install/Uninstall modules/components in joomla admin login. As of now we need to copy paste the com_mvc folder under site/components folders as well. Anyways this is a great tutorial and helped me understand the exact flow in joomla.

Thanks again. 

-
avatar
Quote
- -
Written by Vasan on 11 August 2009

You have explained the concepts so beutifully, you saved me hours of labour, thanks so much

-
avatar
Quote
- -
Written by dhaval on 20 April 2010

great tutorial for beginners....do u also have model part?????

-
avatar
Quote
- -
Written by Hamdy Mokhtar sherif on 21 April 2010

Thanks very much for your help,

realy i enjoyed

-
avatar
Quote
- -
Written by OBS on 06 May 2010

Thanks for this turial...

It's very nice...

-
avatar
Quote
- -
Written by evnix on 23 June 2010

there is a typo

  1. Create folder administrator/components/com_mvc/view/list
  2. Create folder administrator/components/com_mvc/view/list/tmpl
  3. Create file administrator/components/com_mvc/view/list/view.html.php

i tried it but it says view not found,

i tried copying the list folder to the 'views' folder and it worked

-
avatar
Quote
- -
Written by Rajeev Nath Verma on 13 August 2010

This is very good tutorial for the begginers .

-
avatar
Quote
- -
Written by ravi on 04 September 2010

Thanks !

Very nice tutorials !

Waiting for the next part...

-
avatar
Quote
- -
Written by parmjeet on 17 September 2010

Thanks for nice article.

-
avatar
Quote
- -
Written by mak on 01 November 2010

B E A utiful !

Thanks a lot.

-
avatar
Quote
- -
Written by uzzal sarkar on 30 November 2010

Very nice tutorials !

Thanks very much for your help,

-
avatar
Quote
- -
Written by Mohammad hussain on 08 January 2011

Cool  Very nice stuff to learn joomla' component. Thanks

-
avatar
Quote
- -
Written by Ron on 24 February 2011

The folder to download is empty...

-
avatar
Quote
- -
Written by George from Greece on 16 April 2011

Thanks very very much.

It was very helpfull

Thanks

-
avatar
Quote
- -
Written by S.M. Fahad Ali on 21 April 2011

Making every part understandable, Its really great.

-
avatar
Quote
- -
Written by Ken on 21 July 2011

3 years later this is still the best example I have seen.
I have programmed for 40+ years and I found this useful.
The big thing is you went beyond the basic Hello World and showed how the other tasks can be called.  BIG step missing elsewhere.
Thank you for your hard work.

PS Still can't download the files.  WayBack shows that it has always been missing

-
avatar
Quote
- -
Written by Ducky on 24 November 2011

How neat! Is it really this silmpe? You make it look easy.

-
avatar
Quote
- -
Written by raji on 04 February 2012

very nice..

-
Add New Comment
Name:
Email:
Comment:
Attachment
Hide Comment
Security code:
Enter text as you see on image
 
 
What is best way for Download/Installation MightyExtensions?
 


Member Area



Member Activity

We have 1894 guests and 9 members online


MightyTemplate - Professional Joomla Templates