Create object instances, register vars and params into array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
lucaslopatka
Forum Newbie
Posts: 4
Joined: Mon Jun 22, 2009 11:53 pm

Create object instances, register vars and params into array

Post by lucaslopatka »

Hi,

I'm trying to build up a set of classes and methods:

a) coreObject, with subclasses registry, template, component, module, plugin.

b) render, with subclasses xmlParser and writeHTML (that's all for now).

I am using xml based templating, in which template positions may be assigned to a given number of modules, of which there may be multiple instances of a type, and a component, of which only one instance exists... Properties of each object are stored in separate xml files, and are validated against a generic schema.

How can I, and what is the recommended way to load my objects as instances of the original, and register their core properties (and a unique id) into an array in my registry class?

The code for my core functions is (I've removed the code within the subclasses for this post):

Attached to the bottom is a list of array functions that I would like to be able to use in manipulating the registry array keys and values.

**The code is still rough -- what I'm trying to do is break this down into logical steps that don't break OOP principles.

Thanks

Code: Select all

 
class coreObj 
{
 
// Core variables
protected $iscore;
protected $type;
protected $name;
protected $authorName;
protected $authorEmail;
protected $authorURL;
protected $createDate;
protected $copyright;
protected $license;
protected $version;
protected $description;
$files = array();
 
}
 
class registry extends coreObj
{
  function __construct($config = array())
  {
    $this->__construct($config);
  }
}
 
class template extends coreObj
{
}
 
 
class component extends coreObj
{
}
 
class module extends coreObj
{
}
 
class plugin extends coreObj
{
}
 
This is the code for the XML parsing class:

Code: Select all

 
class xmlParser extends render
{
    
    public function validate_xml_config ($xmlFile, $xmlSchema)
    {
 
        $dom = new DomDocument;
        // Load the xml document in the DOMDocument object
        $dom = DOMDocument::load($xmlFile);
        // Validate the XML file against the schema
        if (($dom->schemaValidate($xmlSchema)) == false)
            {
            echo '<pre>';
            throw new Exception ("$xmlFile is an invalid configuration file");
            echo '</pre>';
            //echo "XML config loaded";
            } 
        return true;
    }
    
    public function load_xml_config ($xmlFile, $xmlSchema)
    {
        $dom = new DomDocument;
        // Load the xml document in the DOMDocument object
        $dom = DOMDocument::load($xmlFile);
        // Validate the XML file against the schema
        if ($dom->schemaValidate($xmlSchema))
            {
            null;
            //echo "XML config loaded";
            } 
            else 
            {
            die ("$xmlFile is an invalid config file.");
            }
            $this->dom = $dom; 
    }
    public function getElements($tagName, $xmlFile, $xmlSchema)
    {
        $this->load_xml_config($xmlFile, $xmlSchema);
        $doc = $this->dom->documentElement;
        $objects = $doc->getElementsByTagName($tagName);
        $this->objects = $objects;
    }
    public function loadObjects($tagName, $xmlFile, $xmlSchema)
    {   
        xmlParser::getElements($tagName, $xmlFile, $xmlSchema);
        $i = 0;
        foreach ($this->objects as $object) 
        {
            $type = $object->getAttribute('type');
            switch ($type)
            {
                case 'head':
                    break;
                
                case 'component':
                    //if(file_exists($filepath)) {
                    $name = $object->getAttribute('name');
                    $filepath = PATH_COMPONENTS.DS.'com_'.$name.DS.'index.php';
                        include ($filepath); 
                    //} 
                    break;
                
                case 'module':
                    $name = $object->getAttribute('name');
                    $style = $object->getAttribute('style');
                    $id = $object->getAttribute('id');
                    //echo $type.', '.$name.', '.$style.', '.$id, "\n"; 
                    $filepath = PATH_MODULES.DS.'mod_'.$name.DS.'index.php';
                    if(file_exists($filepath)) {
                        include ($filepath); 
                    }           
                    break;
                
                case 'wrapper':
                    $name = $object->getAttribute('name');
                    $id = $object->getAttribute('id');
                    break;
                
                case 'message':
                    break;
            }
            $i++;
        }
    }
}
class writeHTML extends render
{
    public function iframe($url, $name, $attribs = null, $noFrames = '')
    {
        if(is_array($attribs))
        {
            arrayHelper::toString($attribs);
        }
        return '<iframe src="'.$url.'" '.$attribs.' name="'.$name.'">'.$noFrames.'</iframe>';
    }
    
    function script()
    {
    }
    
    function stylesheet($filename, $path = 'css/', $attribs = array())
    {
        if(strpos($path = 'http') !== 0)
        {
        }
    }
}
 
arrayHelper class:

Code: Select all

 
<?php
class arrayHelper
{
    function toInteger(&$array, $default = null)
    {
        if (is_array($array)) {
            foreach ($array as $i => $v) {
                $array[$i] = (int) $v;
            }
        } else {
            if ($default === null) {
                $array = array();
            } elseif (is_array($default)) {
                arrayHelper::toInteger($default, null);
                $array = $default;
            } else {
                $array = array( (int) $default );
            }
        }
    }
    
    function toObject(&$array, $class = 'stdClass')
   {
       $obj = null;
       if (is_array($array))
       {
           $obj = new $class();
           foreach ($array as $k => $v)
           {
               if (is_array($v)) {
                   $obj->$k = arrayHelper::toObject($v, $class);
               } else {
                   $obj->$k = $v;
               }
           }
       }
       return $obj;
   }
 
   function toString( $array = null, $inner_glue = '=', $outer_glue = ' ', $keepOuterKey = false )
   {
       $output = array();
 
       if (is_array($array))
       {
           foreach ($array as $key => $item)
           {
               if (is_array ($item))
               {
                   if ($keepOuterKey) {
                       $output[] = $key;
                   }
                   // This is value is an array, go and do it again!
                   $output[] = arrayHelper::toString( $item, $inner_glue, $outer_glue, $keepOuterKey);
               }
               else {
                   $output[] = $key.$inner_glue.'"'.$item.'"';
               }
           }
       }
 
       return implode( $outer_glue, $output);
   }
 
   function fromObject( $p_obj, $recurse = true, $regex = null )
   {
       $result = null;
       if (is_object( $p_obj ))
       {
           $result = array();
           foreach (get_object_vars($p_obj) as $k => $v)
           {
               if ($regex)
               {
                   if (!preg_match( $regex, $k ))
                   {
                       continue;
                   }
               }
               if (is_object( $v ))
               {
                   if ($recurse)
                   {
                       $result[$k] = arrayHelper::fromObject( $v, $recurse, $regex );
                   }
               }
               else
               {
                   $result[$k] = $v;
               }
           }
       }
       return $result;
   }
   
    function getColumn(&$array, $index)
   {
       $result = array ();
 
       if (is_array($array))
       {
           $n = count($array);
           for ($i = 0; $i < $n; $i++)
           {
               $item = & $array[$i];
               if (is_array($item) && isset ($item[$index])) {
                   $result[] = $item[$index];
               } elseif (is_object($item) && isset ($item-> $index)) {
                   $result[] = $item-> $index;
               }
               // else ignore the entry
           }
       }
       return $result;
   }
   
    function getValue(&$array, $name, $default=null, $type='')
   {
       // Initialize variables
       $result = null;
 
       if (isset ($array[$name])) {
           $result = $array[$name];
       }
 
       // Handle the default case
       if (is_null($result)) {
           $result = $default;
       }
 
       // Handle the type constraint
       switch (strtoupper($type))
       {
           case 'INT' :
           case 'INTEGER' :
               // Only use the first integer value
               @ preg_match('/-?[0-9]+/', $result, $matches);
               $result = @ (int) $matches[0];
               break;
 
           case 'FLOAT' :
           case 'DOUBLE' :
               // Only use the first floating point value
               @ preg_match('/-?[0-9]+(\.[0-9]+)?/', $result, $matches);
               $result = @ (float) $matches[0];
               break;
 
            case 'BOOL' :
            case 'BOOLEAN' :
               $result = (bool) $result;
               break;
 
           case 'ARRAY' :
               if (!is_array($result)) {
                   $result = array ($result);
               }
               break;
 
           case 'STRING' :
               $result = (string) $result;
               break;
 
           case 'WORD' :
               $result = (string) preg_replace( '#\W#', '', $result );
               break;
 
           case 'NONE' :
           default :
               // No casting necessary
               break;
       }
       return $result;
   }
 
/*    function sortObjects( &$a, $k, $direction=1 )
   {
       $GLOBALS['JAH_so'] = array(
           'key'        => $k,
           'direction'    => $direction
       );
       usort( $a, array('arrayHelper', '_sortObjects') );
       unset( $GLOBALS['JAH_so'] );
 
       return $a;
   }
 
    function _sortObjects( &$a, &$b )
   {
       $params = $GLOBALS['JAH_so'];
       if ( $a->$params['key'] > $b->$params['key'] ) {
           return $params['direction'];
       }
       if ( $a->$params['key'] < $b->$params['key'] ) {
           return -1 * $params['direction'];
       }
       return 0;
   }*/
}
?>
 
User avatar
Darhazer
DevNet Resident
Posts: 1011
Joined: Thu May 14, 2009 3:00 pm
Location: HellCity, Bulgaria

Re: Create object instances, register vars and params into array

Post by Darhazer »

What is the purpose of this line? What you are trying to do with it?

Code: Select all

function __construct($config = array())
  {
    $this->__construct($config); // This one?!
  }
lucaslopatka
Forum Newbie
Posts: 4
Joined: Mon Jun 22, 2009 11:53 pm

Re: Create object instances, register vars and params into array

Post by lucaslopatka »

Load vars from coreObj into an array... then merge another array $options constructed in 'content class extends component' (which in turn extends coreObj), and clone a new object for each module instance.

Here's the what I have for the content class to date:

Code: Select all

 
class content extends coreObj
{
    var $title = '';
    var $description = '';
    var $link = '';
    var $baseURL = '';
    var $language = array();
    var $charset = array();
    var $scripts = array();
    var $script = array();
    var $stylesheets = array();
    var $style = array();
    var $metaTags = array();
    var $published = '';
    
    function setTitle($title)
    {
        $this->_title = $title;
    }
    function getTitle()
    {
        return $this->_title;
    }
    
    function getDescription($description)
    {
        $this->_description = $description;
    }
    function setDescription()
    {
        return $this->_description;
    }
    
    function getLink($link)
    {
        $this->_link = $link;
    }
    function setLink()
    {
        return $this->_link;
    }
    
    function getBaseURL($baseURL)
    {
        $this->_baseURL = $baseURL;
    }
    
    function __construct( $options = array())
    {
        if (array_key_exists('charset', $options)) {
            $this->setCharset($options['charset']);
        }
 
        if (array_key_exists('language', $options)) {
            $this->setLanguage($options['language']);
        }
 
        if (array_key_exists('tab', $options)) {
            $this->setTab($options['tab']);
        }
 
        if (array_key_exists('link', $options)) {
            $this->setLink($options['link']);
        }
 
        if (array_key_exists('base', $options)) {
            $this->setBase($options['base']);
        }
    }
 
    
    // Get layout from URL (required by getView)
    function getLayout($layout) 
    {
        switch($layout)
        {
            case 'blog':
                echo ' and layout as blog';
                break;
            case 'list':
                echo ' and layout as list';
                break;
            case 'add':
                echo ' and add content';
            case 'edit':
                echo ' and edit content';
                break;
        }
        echo '.';
    }
    
    // Get view (section, category, or article) from URL and call layout function. 
    function getView($view, $layout)
    {
        echo "View $view";
        switch($view)
        {
            case 'section':
                $this->getLayout($layout);
                break;
            case 'category':
                $this->getLayout($layout);
                break;
            case 'article':
                $this->getLayout($layout);
                break;
        }
    }
}
 
Post Reply