Getting Started - JObject Topic is solved

Have a programming question regarding your component, plug-in, extension or core hacks? Have an interesting tidbit, FAQ or programming tip you’d like to share? This is the place for you.

Moderators: tjay, seadap, Rogue4ngel, matthewhayashida

uberlandia

Getting Started - JObject

Post by uberlandia » Fri Aug 10, 2007 3:10 am

The JObject class is defined in file object.php.

In a Joomla 1.5 installation, you will find this file under the following path:
libraries/joomla/base/object.php

If you look inside the libraries folder, you will notice that each subfolder corresponds to a Package in the API reference.

The icon for a package folder is Image

The JObject class belongs to the Image Joomla-Framework package. Hence, object.php "belongs to" libraries/joomla/ folder tree.

If you look inside the libraries/joomla package folder, you will notice that each subfolder corresponds to a Subpackage in the API reference.

The icon for a subpackage folder is Image.

The JObject class belongs to the Image Base subpackage. Hence, you will find object.php inside the libraries/joomla/base folder!

It´s easy:

Package
Subpackage
File
Image
Image
Image
Joomla-Framework
Base
object.php
libraries/joomla/
base/
object.php

(See Ian´s comment about this issue in post #17 of this thread.)

As we can read about JObject class at the Developer Wiki,

This is the Joomla! base Object class. It allows __construct and __destruct to be used in PHP4. It is the base class of most of the classes in the Joomla! API. This is an abstract class and defines an interface rather than functionality.


It is an interesting study for some developers since it is a very important class, which... "does nothing" (no functionality)! This characteristic is "omnipresent" in OOP (Object-Oriented Programming) techniques. You do a lot of job that "does nothing". Some beginners just want to write code that DO the THINGS that need to be DONE... By studying the JObject class one can start discovering very interesting and important things... This kind of effort, in fact, is piece of a bigger "foundation" that will allow very "high buildings" in the future... we don´t see the foundations of a building, but without them it couldn´t stand up. You cannot just start building the first floor without building the foundation before. The results will come after...

The icon for a class is Image.

Take a look at the JObject class reference.

Does it seem a little confusing? Probably, if you´re 101!  :)

I don´t know where this will go, I am travelling the path with you!  :laugh:

The following graphic allow us to quickly view the JObject´ methods and how the JObject class relates to the other classes inside the Base subpackage:

Image

Well... I invite you... let´s TAKE A LOOK AT THE CODE... since it is the very BASE of the wonderful, incredible, amazing Joomla! 1.5 Framework and CMS.

The complete source code is avaiable in file object.php
Last edited by uberlandia on Sun Aug 12, 2007 2:48 am, edited 1 time in total.

uberlandia

Re: Getting Started - JObject

Post by uberlandia » Fri Aug 10, 2007 3:30 am

Below, the code of Image JObject class without most comments:

Code: Select all

<?php

class JObject
{
   var      $_errors      = array();

   function JObject()
   {
      $args = func_get_args();
      call_user_func_array(array(&$this, '__construct'), $args);
   }

   function __construct() {}

   function get($property, $default=null)
   {
      if(isset($this->$property)) {
         return $this->$property;
      }
      return $default;
   }

   function getError($i = null, $toString = true )
   {
      // Find the error
      if ( $i === null) {
         // Default, return the last message
         $error = end($this->_errors);
      }
      else
      if ( ! array_key_exists($i, $this->_errors) ) {
         // If $i has been specified but does not exist, return false
         return false;
      }
      else {
         $error   = $this->_errors[$i];
      }

      // Check if only the string is requested
      if ( JError::isError($error) && $toString ) {
         return $error->toString();
      }

      return $error;
   }

   function getErrors()
   {
      return $this->_errors;
   }

   function getPublicProperties( $assoc = false )
   {
      $vars = array(array(),array());
      foreach (get_object_vars( $this ) as $key => $val)
      {
         if (substr( $key, 0, 1 ) != '_')
         {
            $vars[0][] = $key;
            $vars[1][$key] = $val;
         }
      }
      return $vars[$assoc ? 1 : 0];
   }

   function set( $property, $value = null )
   {
      $previous = isset($this->$property) ? $this->$property : null;
      $this->$property = $value;
      return $previous;
   }

   function setError($error)
   {
      array_push($this->_errors, $error);
   }

   function toString()
   {
      return get_class($this);
   }
}

?>

uberlandia

Re: Getting Started - JObject

Post by uberlandia » Fri Aug 10, 2007 4:05 am

Now, let´s see the features... every Image JObject class descendant will inherit!   :pop

*** If you´re new to OOP (Object Oriented Programming), please take a look at the "Objects..." thread or some of the interesting references listed in another post ***

Code: Select all

var $_errors = array();


One "array of errors"? What is this?
Well... it is a very very good and simple idea! Congratulations!
When it happens an error in an Object (any instance of a JObject descendant), informations about the error will be stored in $errors, thus making a standard error history pattern for each Object!

Code: Select all

function __construct() {}


And... what is this?! It´s a "do nothing" constructor. As you should know, the name of this method (__construct) is automatically considered as the constructor for the class... in PHP 5.

BUT, in PHP 4, this is not the case. This function is not a constructor! It is only a "do nothing" function called "__construct"...

In PHP 4, the function automatically considered as the constructor for the class is the function declared inside the class definiton which have the same name of the class. See below:

Code: Select all

   function JObject()
   {
      $args = func_get_args();
      call_user_func_array(array(&$this, '__construct'), $args);
   }


What is happening here? Those two lines are a good lesson in PHP.
First one is easier: $args receive results from func_get_args() which returns an array with the argument values passed to JObject() - the PHP4 constructor for the class.
Second does the following: call_user_func_array() will pass the arguments in $args to a function, defined in the first parameter, which is array(&$this, '__construct')

To understand it, let´s see PHP documentation:

A method of an instantiated object is passed as an array containing an object as the element with index 0 and a method name as the element with index 1.


So, the instantiated object (first element of the array) is &$this, which is a reference to itself ($this), and the method name (second element of the array) is '__construct'.

This will make a call to JObject constructor in PHP 4 - JObject() tranforms into a call to JObject '__construct()' method (the PHP 5 constructor), using the same arguments.

Descendant classes will not have to worry with PHP 4 compatibility - they only need to declare their '__construct' PHP 5 constructor, and when generating a new instance, if the code is runing under PHP 4, the ancestor constructor - JObject() - will transform its call in a call to the '__construct' method of the instance´s class...

??? I don´t know about joombies interest on this topic, but I think every Joomla! developer has to know this things...
Last edited by uberlandia on Sun Aug 12, 2007 2:55 am, edited 1 time in total.

User avatar
CirTap
Joomla! Intern
Joomla! Intern
Posts: 73
Joined: Mon Dec 12, 2005 5:34 pm
Contact:

Re: Getting Started - JObject

Post by CirTap » Fri Aug 10, 2007 4:21 am

WOW!

Excellent work.
Watch out or you'll get hired by Chris or Ian to write more of this :D

CirTap
You can have programs written fast, well, and cheap, but you only get to pick 2 ...

"I love deadlines. I like the whooshing sound they make as they fly by." Douglas Adams

uberlandia

Re: Getting Started - JObject

Post by uberlandia » Fri Aug 10, 2007 4:21 am

Enough of working for today! (local time is 01:17 AM)
Let me know your interest to continue with this dissecation on Joomla´s JObject class in object.php file, and the relevance of this topic in this 101 forum.
And let me know also... are the explanations clear? Confused?
It will be very nice to have feedback from you all.

And thank you, Amy, your feedback motivated me to open this topic. I hope this can be useful for someone.

:)

User avatar
Rogue4ngel
Joomla! Enthusiast
Joomla! Enthusiast
Posts: 199
Joined: Sun Nov 26, 2006 10:46 pm
Location: New York

Re: Getting Started - JObject

Post by Rogue4ngel » Fri Aug 10, 2007 5:06 am

Interesting dissemination; I'm sure someone will find it useful, no doubt.  Thanks for the efforts.
If you're not a part of the solution, you're a part of the problem.

User avatar
Chris Davenport
Joomla! Intern
Joomla! Intern
Posts: 95
Joined: Thu Aug 18, 2005 8:57 am
Location: Shrewsbury, Shropshire, United Kingdom

Re: Getting Started - JObject

Post by Chris Davenport » Fri Aug 10, 2007 10:09 am

Hi uberlandia.

I can see the beginnings of a useful tutorial here. :)  Please, please carry on.

A very frequently used function you might like to look at is jimport.

:pop

Regards,
Chris.
Joomla! Core Team Member | Documentation Working Group Coordinator

"Reality is merely an illusion, although a very persistent one" - Albert Einstein
"We are suspended in language such that we don't know what is up and what is down" - Niels Bohr

User avatar
jalil
Joomla! Enthusiast
Joomla! Enthusiast
Posts: 128
Joined: Wed Jul 04, 2007 4:54 am
Location: Kuala Lumpur, Malaysia
Contact:

Re: Getting Started - JObject

Post by jalil » Fri Aug 10, 2007 12:56 pm

Chris Davenport wrote:Hi uberlandia.

I can see the beginnings of a useful tutorial here. :)  Please, please carry on.

A very frequently used function you might like to look at is jimport.

:pop

Regards,
Chris.


talking of functions, i can't find a convenient list of functions available to the programmer of extensions. be it in 1.0.x or 1.5.x. It's all defined somewhere and everwhere but not in a list, convenient as a look up list.

that this list is missing is somewhat strange to me, as i thought it would the first thing to have before anyone can code anything in whatever language. if you want to code is PHP, besides having to know the language construct, you also need to know that function function mail() for example, already exists, thus it need not be recreated.

so my question is where is the list of functions already existing in joomla that can be used ?
just trying to keep things simple for myself.  :)
Last edited by jalil on Fri Aug 10, 2007 1:10 pm, edited 1 time in total.

User avatar
Chris Davenport
Joomla! Intern
Joomla! Intern
Posts: 95
Joined: Thu Aug 18, 2005 8:57 am
Location: Shrewsbury, Shropshire, United Kingdom

Re: Getting Started - JObject

Post by Chris Davenport » Fri Aug 10, 2007 1:23 pm

There are very few "standalone" functions in the 1.5 Framework.  Almost all functions are methods of classes.  There is a convenient class list in the wiki API reference: http://dev.joomla.org/component/option,com_jd-wiki/Itemid,/id,references:joomla.framework/

However, I agree that some sort of index to function/methods could be useful.  I'll see if I can generate one using phpDocumentor.  One point to note is that quite a few methods have the same name in different classes.  This is quite deliberate of course and shouldn't be a problem.  For example, we have JMenu->getParams(), JComponentHelper->getParams() and JParameter->getParams().

Regards,
Chris.
Joomla! Core Team Member | Documentation Working Group Coordinator

"Reality is merely an illusion, although a very persistent one" - Albert Einstein
"We are suspended in language such that we don't know what is up and what is down" - Niels Bohr

User avatar
ianmac
Joomla! Enthusiast
Joomla! Enthusiast
Posts: 237
Joined: Sat Sep 24, 2005 11:01 pm
Location: Toronto, Canada

Re: Getting Started - JObject

Post by ianmac » Fri Aug 10, 2007 1:31 pm

You can find a list of all classes, methods and properties at:

http://api.joomla.org/elementindex_Joom ... ework.html

Ian
Help test my Component XML Generator Tool!
http://extensions.joomla.org/component/option,com_mtree/task,viewlink/link_id,1997/Itemid,35/
All feedback appreciated!

User avatar
jalil
Joomla! Enthusiast
Joomla! Enthusiast
Posts: 128
Joined: Wed Jul 04, 2007 4:54 am
Location: Kuala Lumpur, Malaysia
Contact:

Re: Getting Started - JObject

Post by jalil » Fri Aug 10, 2007 1:47 pm

Chris Davenport wrote:There are very few "standalone" functions in the 1.5 Framework.  Almost all functions are methods of classes.  There is a convenient class list in the wiki API reference: http://dev.joomla.org/component/option,com_jd-wiki/Itemid,/id,references:joomla.framework/

However, I agree that some sort of index to function/methods could be useful.  I'll see if I can generate one using phpDocumentor.  One point to note is that quite a few methods have the same name in different classes.  This is quite deliberate of course and shouldn't be a problem.  For example, we have JMenu->getParams(), JComponentHelper->getParams() and JParameter->getParams().

Regards,
Chris.


sorry, yes, thats what i meant by functions, it doesnt matter if they are encapsulated under classes. that won't be a problem and is in fact better. thanks for the references.

User avatar
jalil
Joomla! Enthusiast
Joomla! Enthusiast
Posts: 128
Joined: Wed Jul 04, 2007 4:54 am
Location: Kuala Lumpur, Malaysia
Contact:

Re: Getting Started - JObject

Post by jalil » Fri Aug 10, 2007 1:55 pm

ianmac wrote:You can find a list of all classes, methods and properties at:

http://api.joomla.org/elementindex_Joom ... ework.html

Ian


ah ! thanks much. exactly what is needed. who would have guessed it's at api.joomla :)

User avatar
ianmac
Joomla! Enthusiast
Joomla! Enthusiast
Posts: 237
Joined: Sat Sep 24, 2005 11:01 pm
Location: Toronto, Canada

Re: Getting Started - JObject

Post by ianmac » Fri Aug 10, 2007 2:00 pm

jalil wrote:
ianmac wrote:You can find a list of all classes, methods and properties at:

http://api.joomla.org/elementindex_Joom ... ework.html

Ian


ah ! thanks much. exactly what is needed. who would have guessed it's at api.joomla :)


Sorry...  we'll try and find a more logical place for it next time :)

Now...  back to the subject at hand - JObject.

Ian
Help test my Component XML Generator Tool!
http://extensions.joomla.org/component/option,com_mtree/task,viewlink/link_id,1997/Itemid,35/
All feedback appreciated!

User avatar
jalil
Joomla! Enthusiast
Joomla! Enthusiast
Posts: 128
Joined: Wed Jul 04, 2007 4:54 am
Location: Kuala Lumpur, Malaysia
Contact:

Re: Getting Started - JObject

Post by jalil » Fri Aug 10, 2007 2:18 pm

ianmac wrote:
jalil wrote:
ianmac wrote:You can find a list of all classes, methods and properties at:

http://api.joomla.org/elementindex_Joom ... ework.html

Ian


ah ! thanks much. exactly what is needed. who would have guessed it's at api.joomla :)


Sorry...  we'll try and find a more logical place for it next time :)

Now...  back to the subject at hand - JObject.

Ian


they way i see it, an object has properties, methods and classes, and may contain other object/s with thier own properties, methods and classes. This heirarchical object approach to OO programming is what makes life easier.

And my favourite, the functions, reside somewhere in them, thus all that a developer need to do is to find the appropriate 'address'. Should the reference to the object is inappopriate, or invalid, the classsification and extra protection measures within the definition should take care of it, leaving developers free to call any method or create any function, without having to worry about the design methodology of the topmost level. To me, that's what an interface is all about.

Indeed, at times developers make duplicate functions, for the sole purpse of having better control over what they do. Default predefined methods sometimes do not handle errors and abnormalities correctly or in a way preferred by the developer, thus having a user defined object makes for a temporary solution to this while waiting for final adoption into the JObject proper. It would also serve to extend functionality to the Application. However, this is dangerous.

User avatar
AmyStephen
Joomla! Guru
Joomla! Guru
Posts: 579
Joined: Wed Nov 22, 2006 3:35 pm
Location: Nebraska
Contact:

Re: Getting Started - JObject

Post by AmyStephen » Fri Aug 10, 2007 11:42 pm

Uberlandia -

We are very honored to have you with us! Look at the interest you have in this thread! Do you realize that you have attracted the attention of our most Senior Development Documentation Leads and Core Team Members who are smiling because of your work (and thinking about how to utilize your skills best for the community?)

Thanks so very much for joining us and immediately contributing. We are going to learn from you.  8)

Amy :)
~*~ Joomla!'s Queen of the Blues - Jennifer Marriott ~*~
http://OpenSourceCommunity.org/node/1719/

User avatar
AmyStephen
Joomla! Guru
Joomla! Guru
Posts: 579
Joined: Wed Nov 22, 2006 3:35 pm
Location: Nebraska
Contact:

Re: Getting Started - JObject

Post by AmyStephen » Sat Aug 11, 2007 12:30 am

I think I am understanding this and I have looked at that API for along time without any inkling of what it was about. So, this is certainly good for beginners. Sadly, this question will likely expose the fact I am *indeed* a beginner, but, I want to learn, so, I will ask.

++++

uberlandia wrote:If you look inside the libraries folder, you will notice that each subfolder corresponds to a Package in the API reference.


Why is there a Parameter package on the Joomla.Framework page when there is not a corresponding folder?

Amy :) :) :) ... very happy!
~*~ Joomla!'s Queen of the Blues - Jennifer Marriott ~*~
http://OpenSourceCommunity.org/node/1719/

User avatar
AmyStephen
Joomla! Guru
Joomla! Guru
Posts: 579
Joined: Wed Nov 22, 2006 3:35 pm
Location: Nebraska
Contact:

Re: Getting Started - JObject

Post by AmyStephen » Sat Aug 11, 2007 12:40 am

I see how you navigate the API documentation - that is AWESOME and very helpful. But, I do not understand how you located Ian's UML diagram. Where are those kept?

I have to study this several more times and see if I can apply it to other packages.

Excellent.
~*~ Joomla!'s Queen of the Blues - Jennifer Marriott ~*~
http://OpenSourceCommunity.org/node/1719/

User avatar
ianmac
Joomla! Enthusiast
Joomla! Enthusiast
Posts: 237
Joined: Sat Sep 24, 2005 11:01 pm
Location: Toronto, Canada

Re: Getting Started - JObject

Post by ianmac » Sat Aug 11, 2007 12:54 am

Hey!

You can find links to the UML diagrams for each package at: http://dev.joomla.org/component/option, ... framework/
These packages are a little out of date, but not too bad, really...

As for your question about packages and subfolders, it is not an absolute rule that each package is a subdirectory under libraries/joomla.

While this is mostly true, there are some exceptions:
- Table package - these classes are in the database and database/table directory, but are distinct enough from JDatabase to warrant their own package.
- Parameter package - these classes are in the html/parameter directory.  They are related to the HTML package, but again, are distinct enough that they get their own package.

Those are the two main exceptions, really.  You will also notice that some classes are in subdirectories of the main directory (e.g. the button child classes are in /html/toolbar/button and the MVC classes are in application/component.

Hope this helps.
Help test my Component XML Generator Tool!
http://extensions.joomla.org/component/option,com_mtree/task,viewlink/link_id,1997/Itemid,35/
All feedback appreciated!

User avatar
AmyStephen
Joomla! Guru
Joomla! Guru
Posts: 579
Joined: Wed Nov 22, 2006 3:35 pm
Location: Nebraska
Contact:

Re: Getting Started - JObject

Post by AmyStephen » Sat Aug 11, 2007 12:59 am

ianmac wrote:You can find links to the UML diagrams for each package at: http://dev.joomla.org/component/option, ... framework/


Oops!  :-[ That was kind of obvious! You and Chris, and others who have helped you, have accomplished a great deal for us. THANKS!

Amy :)
~*~ Joomla!'s Queen of the Blues - Jennifer Marriott ~*~
http://OpenSourceCommunity.org/node/1719/

uberlandia

Re: Getting Started - JObject

Post by uberlandia » Sat Aug 11, 2007 3:17 am

{  :pop This JPopcorn is tasteful...  }

The true meaning of $this statement is that I have no words to thank you all.

ianmac deep knowledge of the API is very precious, and his supervision and comments here are very good for everyone! Please, keep an eye and keep giving us some LIGHT!

And AmyStephen´s skills to LIGHT our motivation are fantastic. (Are you a JMotivator instance?!)



Before going back to our subject, the Image JObject class, let's exchange some words about OOP...

A class is a definition of a type of object. When a class is instantiated, you have an object of that class.

A class definition (a definition of the definition of an object) consists of the declaration of its properties (data) and methods (actions, or functions).

From "the outside", one may only grasp the interface (public properties and methods) and USE an object of a class. But from "the inside", it means, from the perspective of a developer who wishes to build new classes integrated with the already existent structure, or from the perspective of a joombie who dreams with being a Core Team member  :laugh:, or simply confortably develop Joomla! websites knowing deeply what is happening and what he/she is doing, a knowledge about the BASE is encouraged because it will capacitate the developer to build his/her new classes following the patterns and standards used in the entire existing project - the Joomla-Framework, which is the engine behind the Joomla! CMS.

Well... I don't know yet the framework neither the API, but I am happy to share with you the results of my investigations!

Thank you, jalil, Rogue4ngel, matthewhayashida and all others to create and maintain 101!

As JObject is ancestor of many many classes in the whole framework (all classes, Ian?), everything (properties and methods) declared in its definition will be inherited, and, thus, accessible and usable by every descendant class!

*** See Ian´s answer on post#21, where he also teaches some basic OOP concepts. ***

As we saw, JObject offers a mechanism where you declare a __construct function to your JObject´s descendant class, and IT is the class constructor function even in PHP 4! Never need to bother with this tricky compatibility issue anymore! Just declare your custom class as JObject´s descendant (class MyClass extends JObject).

But this is only one feature. Let's continue and see the others?



Code: Select all

   function get($property, $default=null)
   {
      if(isset($this->$property)) {
         return $this->$property;
      }
      return $default;
   }


What the documentation says about that?

Returns a property of the object or the default value if the property is not set.


For instance: $object->get('property') or $butterfly->get('color') will return the $object->property value, or the $butterfly->color value. I can also define a default return value for the function, in case of the property wasn't set: $butterfly->get('color','blue') (see how it IS different from using $butterfly->color?). If the property was not set and I don't set a default value, the function will return null.

Now let's jump some lines in object.php file, so we can learn a related function, as we can see below. (We should go back after.)

Code: Select all

   function set( $property, $value = null )
   {
      $previous = isset($this->$property) ? $this->$property : null;
      $this->$property = $value;
      return $previous;
   }


[quote=∓quot;Documentation"\]Modifies a property of the object, creating it if it does not already exist.

return: Previous value of the property
[/quote]

This is simple (and powerful). Like love. For instance: $object->set('property','value') or $butterfly->set('color','violet') will set the $object->property value to 'value', or the $butterfly->color value to 'blue'. The return value for the function is the value of the property BEFORE the new value attribution (or null, in case of the property wasn't set).

So, $object->set('property', $object->set('property', $anything)) won't change the property and will return $anything!  :laugh:

Curiously, $butterfly->set('color') will set the color property to null, as the second parameter is missing and its default value is null.

Now, you start to know what Johan carefully built for us.

Together, we will rise people's consciousness and save the planet! I don't eat meat nor sugar.
Last edited by uberlandia on Sun Aug 12, 2007 3:01 am, edited 1 time in total.

uberlandia

Re: Getting Started - JObject

Post by uberlandia » Sat Aug 11, 2007 3:36 am

A commentary:

Educate the developer to use $object->set('property', 'value') to set a property value and $object->get('property', 'default') to get, instead of just use $object->property to both get and set property values may sound strange for begginers, but it is a very good habit, since it will transform in the future in never imagined before enhancements, like a LOG or DEBUGGING feature, only by rewriting JObject´s SET and GET functions and coding them to write the get/set info in a file or database. This is just to give an idea of how good is to practice good habits.

Another example, and more realistic, is to REDEFINE the get/set methods in a descendant class, which can perform more powerful tasks, but using the same and simple and padronized-standard-easy-to-understand syntax in the function call. For example: $cdplayer->set('track',4) - with this call, not only $cdplayer->track will be set to 4, but also the track will play! Of course, the developer needs to declare a function in the descendant class with the same name (set) and code the script to play the track. To change the property value, he/she can call the parent´s set function.

I should already be in bed. MAY ALL BEINGS BE HAPPY! Good night...
Last edited by uberlandia on Sat Aug 11, 2007 3:40 am, edited 1 time in total.

User avatar
ianmac
Joomla! Enthusiast
Joomla! Enthusiast
Posts: 237
Joined: Sat Sep 24, 2005 11:01 pm
Location: Toronto, Canada

Re: Getting Started - JObject

Post by ianmac » Sat Aug 11, 2007 4:08 am

As JObject is ancestor of many many classes in the whole framework (all classes, Ian?), everything (properties and methods) declared in its definition will be inherited, and, thus, accessible and usable by every descendant class!


Many, but certainly not all...  first, there are many singleton classes that are not made into objects, so they are not derived from JObject.  There are others as well that are not for various reasons.

But most classes that you would instantiate would be derived from JObject, yes.

And as a side...  as we venture into object oriented programming, it is important to note that it is called 'object' oriented for a reason.  Before object oriented programming (OOP), everything was based on functions and variables.  So, you might have three variable: $height and $weight and $name.  These variables would be used to store a person's name, height and weight.  You might then have a function called calculateBMI(), which would accept as parameters $height and $weight.  This would look something like:

Code: Select all

function calculateBMI( $height, $weight ) {
    return $weight / $height;
}

But it is very easy to lose track of all these variables...  so the idea behind objects is to encapsulate this data and the functions to manipulate it into one package.  The definition of this package is called a class.  So we might have:

Code: Select all

class person
{
    var $name;
    var $height;
    var $weight;

    function getBMI() {
        return $this->weight / $this->height;
    }
}


Then, if you want to create an object which represents a person, you would do:

Code: Select all

$person = new person();

This is called instantiating the class, because it creates an object (or instance) of the class.

Now, as uberlandia was saying, you can modify the variables (which are called properties), using:

Code: Select all

$person->height = 2;
$person->weight = 50;

Then you can invoke its functions (which are called methods) using:

Code: Select all

$bmi = $person->getBMI();


Now, if we were to make person a child class of JObject, then we would inherit the capabilities of the JObject class.  We would then change the definition to something like:

Code: Select all

class person extends JObject
{
    var $name;
    var $height;
    var $weight;

    function getBMI() {
        return $this->weight / $this->height;
    }
}

Then we could manipulate our person using the get() and set() methods:

Code: Select all

$person->set( 'name', 'Bob' );
$person->set( 'height', 2 );
$person->set( 'weight', 50 );
$person->get( 'weight' );
echo $person->getBMI();


You will notice the use of $this inside classes a lot.  $this is a reference to the current object.  So if I am inside a class, and I use say $this->height = 2;, then that means I am setting the property 'height' of the current object to 2.  When we use $this->height, we aren't talking about any height, but we're talking about the current object height.



Ian
Help test my Component XML Generator Tool!
http://extensions.joomla.org/component/option,com_mtree/task,viewlink/link_id,1997/Itemid,35/
All feedback appreciated!

User avatar
bascherz
Joomla! Intern
Joomla! Intern
Posts: 86
Joined: Mon Jan 16, 2006 1:33 am
Location: Vienna, VA
Contact:

Re: Getting Started - JObject

Post by bascherz » Sat Aug 11, 2007 5:45 pm

I just want to chime in here to say how remarkable this thread is, thanks mainly to uberlandia (you too, Ian). For someone so young (as your avatar makes you appear), you have a lot of insight into not only the OO topic but a quick grasp of WHY the core team wrote the JObject class the way they did. All this and in addition, even though it would appear English is not your primary language, you are unusually articulate for someone so young. In short, YOU ROCK!

The core team should be very interested and watchful of this young lad. He has a lot to offer, perhaps even some translating.
__________________
Bruce Scherzinger

User avatar
Rogue4ngel
Joomla! Enthusiast
Joomla! Enthusiast
Posts: 199
Joined: Sun Nov 26, 2006 10:46 pm
Location: New York

Re: Getting Started - JObject

Post by Rogue4ngel » Sat Aug 11, 2007 9:16 pm

It does sound easy when it's explained, doesn't it. :).  Rest assured, with information like this, and a little hands on work, I think we'll make coders out of everyone!
If you're not a part of the solution, you're a part of the problem.

uberlandia

Re: Getting Started - JObject

Post by uberlandia » Sat Aug 11, 2007 10:55 pm

$uberlandia->set('primarylanguage', 'portuguese');
$uberlandia->set('age', '28yo');
$uberlandia->set('avatar_age', 'around 21yo');

Believe it or not, what attracted me to Joomla! was the OM in the middle: "joOMla"

Image

I´m only a joombie and I want to learn the Joomla-Framework and its API so I can build Joomla! sites with more control than just the admin interface.

For now, my immediate goal is to finish the already started JObject analysis, and nothing more. The positive feedback and the entertainment I am having doing this is making me spent the time I don´t have to write $this.

$thread->set('goal', 'JObject study');

:-* Love is the power that moves everything.



Let´s review JObject´s methods list:

  • __construct
  • JObject
  • get
  • getError
  • getErrors
  • getPublicProperties
  • set
  • setError
  • toString

The respective Method Summary in the API reference have more information.

We already saw "__construct", "JObject", "get" and "set". Let´s go on in the following order:

  • toString
  • setError
  • getError
  • getErrors
  • getPublicProperties

I decided to look at toString first because of its simplicity and because it is an opportunity to talk a little more about OOP.

Code: Select all

   function toString()
   {
      return get_class($this);
   }


[quote=∓quot;Documentation"\]Object-to-string conversion.

Each class can override it as necessary.[/quote]

The php function get_class returns the name of the class of the object passed as its parameter.

In this case, the object is $this.

[quote=∓quot;Ian"\]You will notice the use of $this inside classes a lot.  $this is a reference to the current object.  So if I am inside a class, and I use say $this->height = 2;, then that means I am setting the property 'height' of the current object to 2.  When we use $this->height, we aren't talking about any height, but we're talking about the current object height.
[/quote]

So, if I have an instance of JObject:

Code: Select all

$swirx = new JObject;


And I call its toString method:

Code: Select all

$result = $swirx->toString();


What the result will be? It will be the string "JObject", which is the name of $swirx's class!

So, why not just call get_class($swirx)? Why not simply use the string "JObject"? Well... looking only for the JObject class, ignoring all its connections and descendants, and the fact that JObject is a BASE, a "foundation", a building block for building bigger things, we have no answer.

Now, looking by the OOP perspective, each descendant class will inherit JObject properties and methods. Look:

Code: Select all

class MyClass extends JObject {}
$myObject  = new MyClass;
$result = $myObject->toString();


In this case, $result will be the string "MyClass". It is interesting "toString" will bring a different result depending of from which JObject´s descendant class the object is

But, as the documentation says, "each class can override it as necessary". It means that each class can specify a different way to transform the object of that class into a string.

One benefit of declaring the method in the ancestor class (the base) is that we already have a standard method call that can be used with objects of all the hierarchy, no matter from which descendant class it is.

User avatar
jbruni
Joomla! Apprentice
Joomla! Apprentice
Posts: 37
Joined: Sat Oct 07, 2006 12:36 pm
Location: Uberlândia, MG, Brazil

Re: Getting Started - JObject

Post by jbruni » Sun Aug 12, 2007 3:30 am

Now let´s see JObject´s setError method:

Code: Select all

   function setError($error)
   {
      array_push($this->_errors, $error);
   }


Simple: calling $object->setError('Couldn´t cast the spell.');  you sign an error in the array of errors ("error history") of the object. In this example, we used a simple string, but the $error parameter doesn´t necessarily need to be a string. It may be a JException.

User avatar
jbruni
Joomla! Apprentice
Joomla! Apprentice
Posts: 37
Joined: Sat Oct 07, 2006 12:36 pm
Location: Uberlândia, MG, Brazil

Re: Getting Started - JObject

Post by jbruni » Mon Aug 13, 2007 6:18 am

Let´s continue, let´s finish our Image JObject class review.

Everyone here must be a JObject expert after this thread is concluded.

This ain´t much, just a little first step, but worthwile since someone can get enlightened by being able to understand the mistery of the atom nucleous hidden in object.php lines!  :laugh:  Yes! The atom nucleous! Your body is full of them: you should comprehend them!



We saw we can setError. Now we'll see we can also getError:

Code: Select all

<?php
   function getError($i = null, $toString = true )
   {
      // Find the error
      if ( $i === null) {
         // Default, return the last message
         $error = end($this->_errors);
      }
      else
      if ( ! array_key_exists($i, $this->_errors) ) {
         // If $i has been specified but does not exist, return false
         return false;
      }
      else {
         $error   = $this->_errors[$i];
      }

      // Check if only the string is requested
      if ( JError::isError($error) && $toString ) {
         return $error->toString();
      }

      return $error;
   }
?>


Humm... this method get two parameters, both are optional. If I call it with no parameters:
$object->getError();
it will return me the last item of the _errors array, wich is our "error history", so it means it will return the most recent error signed to $object.
See in the code: end($this->_errors);

The first parameter is the error index that I want to get. For example:
$object->getError(2);
means I want to get the third error (the index of the first array element is zero, the second is one, so the third is two)

If I pass an index that does not actually exist in the array, the result will be false.
In our example, if there is no third error, the result will be false.
If there is, I'll get what I want.

Finally, the second parameter, of which the default value is true...
As said earlier, JObject´s array of errors can have elements of two types: string or JException.
Well, I don´t know anything about JException yet, as I am a 101 joombie starting my journey with JObject!
But, we are smart enough to understand JObject´s getError code and make some explanations without further researches.
Let´s see the second parameter ($toString) treatment inside getError function:

Code: Select all

      if ( JError::isError($error) && $toString ) {
         return $error->toString();


We can deduce that JError::isError is a static JError class method that verifies if the variable passed as its parameter is an object of some error classes (as JException certainly is) and returns true or false, accordingly.

* If something in the statement above didn´t make sense to you, it is worthwile to make an effort to understand it well. It will improve your skills. *

In other words: if the second parameter is set to false and the element found in the errors array is not a string, but a JException object, then the method will not return a string, but a JException object. This happens only if I set the second parameter to false, because if it is set to true (the default), the method will return the result of a toString method call from the respective JException object. It means, it will return the JException object transformed into a string by the JException class own toString method!

In another words: in my particular JObject instance, I save the errors in the errors array using JException objects, instead of just simple strings. Then, if I want to getError to return me string, I use:
$object->getError(2);
But, if I want to getError to return me JException, I'll use:
$object->getError(2, false);

:pop  It was so nice to write those lines. I enjoyed it.
Last edited by jbruni on Mon Aug 13, 2007 6:32 am, edited 1 time in total.

User avatar
jbruni
Joomla! Apprentice
Joomla! Apprentice
Posts: 37
Joined: Sat Oct 07, 2006 12:36 pm
Location: Uberlândia, MG, Brazil

Re: Getting Started - JObject

Post by jbruni » Mon Aug 13, 2007 6:33 am

Now I´m curious about JException and JError classes...

It will be excellent to know the J! way to handle exceptions...

Thinking well, it is also a good thing to know from the beginning, as every code should handle exceptions, and if we know how to do it the J! way, we will be able to do J! compatible code using the J! Framework friendly...

JAY JAY JAY

Hope to be back tomorrow...  this sunday was my first father´s day as a father! ... I´ll go to sleep now...

:)
Last edited by jbruni on Mon Aug 13, 2007 6:43 am, edited 1 time in total.

User avatar
jbruni
Joomla! Apprentice
Joomla! Apprentice
Posts: 37
Joined: Sat Oct 07, 2006 12:36 pm
Location: Uberlândia, MG, Brazil

Re: Getting Started - JObject

Post by jbruni » Tue Aug 14, 2007 2:27 am

The getErrors method of the JObject class is quite simple to understand and to use and to analyse its code:

Code: Select all

   function getErrors()
   {
      return $this->_errors;
   }


[quote=∓quot;Documentation"\]Return all errors, if any[/quote]

A call to $object->getErrors(); and I have all error history from a JObject (or descendant) instance.

User avatar
jbruni
Joomla! Apprentice
Joomla! Apprentice
Posts: 37
Joined: Sat Oct 07, 2006 12:36 pm
Location: Uberlândia, MG, Brazil

Re: Getting Started - JObject

Post by jbruni » Tue Aug 14, 2007 3:13 am

Finally, the getPublicProperties method:

Code: Select all

   function getPublicProperties( $assoc = false )
   {
      $vars = array(array(),array());
      foreach (get_object_vars( $this ) as $key => $val)
      {
         if (substr( $key, 0, 1 ) != '_')
         {
            $vars[0][] = $key;
            $vars[1][$key] = $val;
         }
      }
      return $vars[$assoc ? 1 : 0];
   }


[quote=∓quot;Documentation"\]Returns an array of public properties[/quote]

A call to $object->getPublicProperties(); will return an array with all public properties' names defined for the $object.

A call to $object->getPublicProperties(true); will return an indexed array where the keys are the public properties' names and the values are the respective properties values.

The code of the getPublicProperties method is quite simple to understand, and based upon the PHP get_object_vars function.

The main thing here is the difference between Image public and Image private properties.

The standard used in the Joomla! Framework is to start the name of the property that is meant to be private with the underscore character. So, every private property's name starts with "_"

Private properties should be accessed only inside the class where they are defined.

In JObject class, we have one private property, which is the "_errors" array.
The '_' in the beginning of its name indicates to everybody that this property is a private property.
So, one should never access $object->_errors directly. In this particular case, one should use $object->getErrors()

The getPublicProperties method returns only the Image public properties by verifying the first character of all properties. Is it a underscore? If yes, it is considered Image private and it is NOT included in the result. If no, it is considered Image public and it IS included in the result.


Post Reply