Xtremax - Web Design

18 Mar, 2009

Inside Joomla MVC Part 2

Posted by: Mr Cheetah In: test category

Special Episode : How the magic is done
(requested by james)

It is some times quite confusing to use Joomla MVC, as we are quite often not sure where are the related files are included and how the respective controller/ model/ view are found and invoked. This post is trying to answer that question.

0. Naming Convention

image

The naming convention is some how annoying in Joomla MVC. The class name is quite consistent which is always:

[COMPONENT_NAME][CLASS_TYPE][ITEM_NAME]

For example:

  • SchoolControllerStudent, is a JController instance dealing with Student operations of School component (com_school).
  • SchoolModelTeacher is Teacher model of School component.
  • SchoolViewAttendance is Attenance view of School component.

so far so good, why is it annoying? when the file name comes in, see the below table:

Class Name sits in folder File name
SchoolController / controller.php
SchoolControllerStudent /controllers student.php
SchoolModelTeacher /models teacher.php
SchoolViewAttendance /views/attendance view.php

For controller, there are 2 cases, the default controller, which will sit in the “/” folder location and always named controller.php, and when there are more than one controller, they’ll be put in “/controllers/” and named based on its purpose. Actually, its filename will match a “controller” parameter in the request. See the standard code piece below in the entry point file:

// Require specific controller if requested
if($controller = JRequest::getWord(’controller’)) {
    $path = JPATH_COMPONENT.DS.’controllers’.DS.$controller.’.php’;
    if (file_exists($path)) {
        require_once $path;
    } else {
        $controller = ”;
    }
}

For the Models, it is very simple, just follow the item name and place them in “/models"/” folder will do the job.

For the Views, it is again becoming irritating, the php file is always called “view.php”, instead, the subfolder name need to match the class name this case: “/views/[VIEWNAME]/view.php”. Add to the complexion, the is always a “tmpl” template folder, inside there “default.php” is for the default layout, all other files corresponds to the layouts same to their filenames.

—— The blog entry starts here officially ——

There are many magical methods in the Joomla MVC API, they automatically find the correct php file (as long as you’ve put them in the correct folder) and initiate a instance when needed. Let’s see a list of them:

  • *.getName()
  • JModel.getInstance($type, $prefix = ”, $config = array())
  • JModel.getTable($name=”, $prefix=’Table’, $options = array())
    use $this->getName() if $name is empty;
  • JView.get($property, $default = null)
  • JView.getModel($name = null)
  • JController.getModel($name = ”, $prefix = ”, $config = array());
  • JController.getView($name = ”, $type = ”, $prefix = ”, $config = array())

JModel is initiated in JController and passed to JView.setModel in JController.display

 
1.*.getName()

They all share a very similar getName() method, which basically return the “name” of the model / view / controller.

First of all, let’s take a look at the regular expression they used in the three classes for .getName() method

Type Regular Expression Match
Group
Eg Result
JModel /Model(.*)/i 1 SchoolModelStudent Student
JView /View((view)*(.*(view)?.*))$/i 3 SchoolViewTeachers Teachers
JController /(.*)Controller/i 1 SchoolController
SchoolControllerStudent
School
School

As we mention before, as the controller will be picked at the component entry point (part 0), there is no way that 2 controller having the same “name” being run at the same time.

 
2. JModel.getInstance()

This is the actual place where every JModel is being initiated, it search for a file named “$type”.php in the included paths:

$modelClass    = $prefix.ucfirst($type);
$path = JPath::find(
    JModel::addIncludePath(),
    JModel::_createFileName( ‘model’, array( ‘name’ => $type))
);
require_once $path;
$result = new $modelClass($config);

Where did we set the include path? it is done automatically in JControllers constructor:

$this->addModelPath($this->_basePath.DS.’models’);

This behavior matches what we have in part 0, where all the models are inside “/models” directory.

 
3. JModel.getTable()

This method by default would search for a JTable class having the same name as the model itself, eg:

SchoolModelTeacher.getTable() = new TableTeacher()

It can be seen very obviously here in the JMode and JTable code:

JModel:
$prefix = ‘Table’
$instance =& JTable::getInstance($name, $prefix, $config );

JTable:
$tableClass = $prefix.ucfirst($name);
$path=JPath::find(JTable::addIncludePath(), strtolower($type).’.php’)
$instance = new $tableClass($db);

Similar to how the JModel include path is added, JTable include path is automatically added in JModel’s constructor:

if (array_key_exists(’table_path’, $config)) {
    $this->addTablePath($config['table_path']);
} else if (defined( ‘JPATH_COMPONENT_ADMINISTRATOR’ )){
    $this->addTablePath(JPATH_COMPONENT_ADMINISTRATOR.DS.’tables’);
}

One interesting point we can see is it will only automatically load the JTable class from the administrator component. That’s why we only see JTables in the administrator component, but not the front end component. The actual reason is unknown for me.

 
4. JView.get($property)

This is another magic method, although we normally only call it by one way get(“data”). What it does is automatically construct the JModel with the same name and call the method “get[PROPERTY]” of that JModel. Eg:

SchoolViewTeachers.get(“data”) ==> SchoolModelTeachers.getData();

SchoolViewStudent.get(“name”) ==> SchoolModelStudent.getName();

The code that illustrate this is here (modified):

$model = $this->_defaultModel;
$method = ‘get’.ucfirst($property);
$result = $this->_models[$model]->$method();

Where does the “_defaultModel” coming? It is actually called from the “display” task of the JController:

$model = & $this->getModel($viewName)
$view->setModel($model, true);

So the overridden JView class can easily take out the correct data form the JModel and put into request then the controller would pick the correct layout and renders to the users.

 
5. JView.getModel()

This method DOES NOT CREATE a JModel object, instead, it just try to load the JModel from its models hash map, normally the default model is set when the “Display” method of JController is called.

 
6. JController.getModel()

This is where the JModel is really created everytime, it is the beginning point where JModel.getInstance is called:

$name = $this->getName();
$prefix = $this->getName() . ‘Model’;
$model = & $this->_createModel( $name, $prefix, $config )

 
7. JController.getView()

Simillar to above, this is where the JView objects are actually being created, based on the directory structure. The actual code is more complicated (as there is a more complicated directory structure), but serve the same function.

Bookmark and Share

18 Mar, 2009

Logging in Joomla

Posted by: Mr Otter In: Joomla

Well, I never had to build such a big system in Joomla so I have never bothered about infrastructure plumbing codes like logging.

Logging is one of the most important aspects of application development.  It allows the developers to track errors that have occurred without needing to reproduce them.  Theoretically, we should be able to figure out what went wrong, simply by looking at a well logged system!

Apparently, joomla does have certain log management system at:

http://www.theartofjoomla.com/reference/12-the-joomla-framework/30-logging-to-files.html

Only problem is… it kind of lacks the control of log4j.  There are a few common problems which have not been addressed:

  • Different levels of logging to allow developers to easily turn on/off logging for performance reasons.
  • File rotation – this is very important.  have seen my catalina.out grow to over 30 GB just because it is not rotated!
Bookmark and Share

18 Mar, 2009

Joomla Jimport

Posted by: Mr Otter In: Joomla

I was looking through the Joomla jimport.  It sure reminded me of the way java did its packaging.  Hmm. after some digging through, i find it pretty innovative.  Joomla actually have some kind of delayed loading mechanism, so that they only load the file when the Class has actually been called. 

This is best illustrated by the piece of code below.

image

I also find the following article informative:

http://blog.joomlatools.eu/2007/12/joomla-15-using-jfactory-and-jimport.html?disqus_reply=7311119#comment-7311119

Besides explaining jimport, it also talks a little about how JFactory can be used to get Joomla objects.

Bookmark and Share

17 Mar, 2009

Adobe Photoshop Secret Shortcuts

Posted by: Dodo bird In: Photoshop| Web Design

Adobe Photoshop shortcuts I find it cool and also learned a lot through this Photoshop Secret Shortcuts. Just want to tell that the doing with lots of clicks is much easier and timesaving then using the keyboard shortcuts keys. Basically working with Photoshop can be very time consuming for both interns and experts. Key board shortcuts are a simply way to bypass a few mouse clicks when doing tool, fonts, colors change. They feel a little bit difficult in the start but once when you pick it up you’ll never go back and you also find it helpful then the using mouse.

Here are 30 of the Photoshop Secret Shortcuts. Check out the link
http://www.webdesignerwall.com/tutorials/photoshop-secret-shortcuts/

Bookmark and Share

17 Mar, 2009

Inside Joomla MVC

Posted by: Mr Cheetah In: test category

MVC architecture is one of the most common and popular architectures for software developments today, especially for web applications.

Then I come across the Joomla MVC architecture, the way Joomla use MVC is a little bit different from what I used to have in JAVA, and the most difficult part is there are some hidden “Magical” links that make the whole MVC API work.

1. Terms and definition

    There are a few major players in the Joomla MVC API namely:
  • JTable
  • JModel
  • JView
  • JController
  • JFactory

Let us look at their use one by one.

1.1 JTable

Strictly speaking, we can consider JTable not part of the Joomla MVC API. In fact, it existed since Joomla 1.0, long before Joomla MVC came out. And it is not even in the same package folder, being under “database folder”, instead of “application” folder where JModel, JView and JController are placed.

But why would I mention it here? First of all, from my opinion, JTable is a closer resemble of what we call “Model” in java programming, which model is a direct mapping of a database item. Secondly, most of the actual data manipulation operations in Joomla MVC are done through JTable.

 

What to do with JTable

There are 3 private variables in JTable:

  • $_tbl         – The Table Name
  • $_tbl_key – Primary Key Column name
  • $_db         – Database connector

To use JTable, we must extend it first, create a file having a special name, for example:

Table File Name Class Name
STUDENT student.php TableStudent
EXAM exam.php TableExam

The reason for this special naming convention is, as i would show later, Joomla is doing some magic behind the scene. Place the php file in the “administrator/com_YOURCOMPONENT/tables” folder.

Then populate it with the fields that we want want this class to have, in other words, what are the database columns need to be mapped to this class.

Then create a constructor that tells the JTable what is the table name and primary key as shown below:

        function __construct(&$db)
        {
                parent::__construct( '#__recipes', 'id', $db );
        }

The next step , is to tell Joomla include the Class file, this should be usually done in the component entry point:

 
JTable::addIncludePath(JPATH_ADMINISTRATOR.DS.'components'.DS.'com_YOURCOMPONENT'.DS.'tables');
 
Why is it useful

To understand why is it useful, let’s look at some methods it provides:

  • bind
  • check
  • store
  • load
  • delete
  • reset
    Bind would copy the data from a associative array (hash map) or and object (stdobj) to the current JTable instance. This is just like we use BeanUtils in java to copy a web form to a POJO.

Check is the method should always be overridden unless nothing need to be checked. Although the check function is not normally automatically called, but it gives us a good entry point where all the validation code should go. Joomla usually use this method to populate fields using default formula if left empty.

Store is the method where the data is actually being persisted into the database.

Load – self explained

delete – self explained

reset – clear all the data fields except the primary key

By using these a few methods, all the common single item database operation can be achieved.

But that is not all yet, let’s look at the following methods, they will make your life much better as they provide quite some joomla specific common functions:

checkin/checkout / isCheckedOut– the joomla checkin checkout function if the database table supports that column

image

publish / unpublish – The publish / unpublish function

image

order / getNextOrder / reorder / Move – the ordering functions

image

hit – hit counter increment

image

savedifferent from store. The save function actually calls the following functions in order, and fails if any of them failed:

  1. bind
  2. check
  3. store
  4. checkin
  5. reorder (if supported)
Bookmark and Share

17 Mar, 2009

Logging in .NET

Posted by: Mr Otter In: .NET

If you have experience in Java, you will be familiar with the myriad of logging frameworks.  One of the important things about logging is that it allows you to actually trace errors that have occurred in your absence.  Without logging, it will be like a crime committed without any trails to investigate.  Logging creates trails when the next application bug is activated.

Snooped around a little before finding a framework which looks pretty extensible like the java one…

http://www.theobjectguy.com/dotnetlog/Overview.aspx

Bookmark and Share

15 Mar, 2009

Social Networking

Posted by: Mr Otter In: SEM

I recently speed up my participation with the social networking sites. May be this is because of the increasing influence of these sites over the web. Second and more valid reason is social networking being a tool for Search Engine Marketing. There are many web sites available to support your appetite. Friendfeed already have 62 services and there can be more not supported yet.

It was very difficult to manage all the sites personally and updates on them. So I did a little trick to make some sort of topology for my social networking web sites.

Read the rest of this entry »

Bookmark and Share

15 Mar, 2009

Google Map Widget

Posted by: Mr Otter In: google| javascript| technology

Well, after playing with it a little bit more, just enhanced it a little to be displayed in a configurable widget.  Of course.. .this is only the beginning… haha.. more fun things are coming up!

Stay tuned!

http://www.widgetbox.com/widget/singapore-maps

Bookmark and Share

15 Mar, 2009

Google Maps - Its Fun!

Posted by: Mr Otter In: google| technology

Well, just spent today browsing through some of the Google Maps API and was really surprised at how easy google made it.  Hmmm.. if only coding was so simple… it would have been a lot, lot more fun… :P

Anyway after a few hours of work, here goes my little map!

http://xtremax.com/googleMap/

Bookmark and Share

13 Mar, 2009

5.1 million dollars for a domain

Posted by: Mr Otter In: Tech Talk

Well, never thought a domain could costs that much… but apparently, ToysRUs really paid that amount for toys.com.

Hmmm.. why didn’t I buy up all the domain names when the internet was still in its infancy?  darn…

http://www.techcrunch.com/2009/02/27/toysrus-buys-toyscom-at-auction-for-51-million/

Bookmark and Share

Xtremax Web Design Portfolio

    Opera Estate Primary SchoolNational Association of Travel Agents SingaporeFUMIYAMA CORPORATIONEngineering Education PortalBOON HI-TECH SUPERSTORESingapore Tourism Board

About Xtremax

This is all about a group of hard-core web developers who go about rambling about their daily efforts to make the internet world a better and more accessible place.