xoops forums

hervet

Friend of XOOPS
Posted on: 2009/8/14 16:36
hervet
hervet (Show more)
Friend of XOOPS
Posts: 2267
Since: 2003/11/4
#1

A singleton to access your data classes

If you are using xoopsObject to manage the data access to your modules tables you must surely use this kind of code:
$myHandler xoops_getmodulehandler('mytable''mymodule');


The problem is that sometimes you declare this kind of code somewhere and you can't access it somewhere else, for example from a function.
The other problem is that you have to repeat this kind of code each time you need a handler.

With this class, you can access to any table's handler from anywhere without multiplying the objects.
You just need to do something like this :
$oledrion_handlers oledrion_handler::getInstance();
$count $oledrion_handlers->h_oledrion_products->getRecommendedCount();


You can even access a handler like this:
$count oledrion_handler::getInstance()->h_oledrion_products->getRecommendedCount();


The advantage, as I said, is that you can access your handlers from anywhere without creating several times the same object and all your handlers are centralized in one place.
Handlers are loaded on demand and stay in memory for further use.

<?php
/**
 * ****************************************************************************
 * oledrion - MODULE FOR XOOPS
 * Copyright (c) Hervé Thouzard of Instant Zero (http://www.instant-zero.com)
 *
 * You may not change or alter any portion of this comment or credits
 * of supporting developers from this source code or any supporting source code
 * which is considered copyrighted (c) material of the original comment or credit authors.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 *
 * @copyright       Hervé Thouzard of Instant Zero (http://www.instant-zero.com)
 * @license         http://www.fsf.org/copyleft/gpl.html& ...  public license
 * @package         oledrion
 * @author             Hervé Thouzard of Instant Zero (http://www.instant-zero.com)
 *
 * Version : $Id:
 * ****************************************************************************
 */

/**
 * Chargement des handlers utilisés par le module
 */
class oledrion_handler
{
    
/**
     * Contient la liste des handlers disponibles
     *
     * @var array
     */
    
private $handlersNames = array('oledrion_manufacturer''oledrion_products''oledrion_productsmanu''oledrion_caddy''oledrion_cat''oledrion_commands''oledrion_related''oledrion_vat''oledrion_votedata''oledrion_discounts''oledrion_vendors''oledrion_files''oledrion_persistent_cart''oledrion_gateways_options');

    
/**
     * Contient l'unique instance de l'objet
     * @var object
     */
    
private static $instance false;

    
/**
     * Réceptacle des handlers
     *
     * @var array
     */
    
public static $handlers null;

    
/**
     * Méthode chargée de renvoyer les handlers de données en les chargeant à la volée
     *
     * @param string $name
     * @return mixed    Null si on échoue, sinon l'objet demandé
     */
    
function __get($name)
    {
        if(
substr($name02) != 'h_') {
            return 
null;
        }
        if(!
in_array(substr($name2), $this->handlersNames)) {
            return 
null;
        }
        if(!isset(
$this->handlersNames[$name])) {
            
$this->handlers[$name] = xoops_getmodulehandler(substr($name2), OLEDRION_DIRNAME);
        }
        return 
$this->handlers[$name];
    }

    private function 
__construct()
    {
        
$this->handlers = array();
    }

    
/**
     * Retourne l'instance unique de la clanss
     *
     * @return object
     */
    
public static function getInstance()
    {
        if (!
self::$instance instanceof self) {
              
self::$instance = new self;
        }
        return 
self::$instance;
    }
}
?>


Note, this class requires Php 5.

hackbrill

Friend of XOOPS
Posted on: 2009/8/14 18:12
hackbrill
hackbrill (Show more)
Friend of XOOPS
Posts: 283
Since: 2005/7/14
#2

Re: A singleton to access your data classes

Thanks for sharing this information.

JulioNC

Quite a regular
Posted on: 2009/8/15 6:03
JulioNC
JulioNC (Show more)
Quite a regular
Posts: 239
Since: 2004/10/8
#3

Re: A singleton to access your data classes

Quote:

hervet wrote:

The advantage, as I said, is that you can access your handlers from anywhere without creating several times the same object and all your handlers are centralized in one place.
Handlers are loaded on demand and stay in memory for further use.


You should look for Registry pattern

trabis

Core Developer
Posted on: 2009/8/15 12:19
trabis
trabis (Show more)
Core Developer
Posts: 2268
Since: 2006/9/1 1
#4

Re: A singleton to access your data classes

Quote:

JulioNC wrote:
You should look for Registry pattern


Important thing here is:

"Handlers are loaded on demand and stay in memory for further use."

Only thing I don't like here is the hardcoded $handlersNames

A more convinient way would be:
Xoops_Module_Helper::getInstance('oledrion')->getHandler('products')->getRecommendedCount();


This a test page for a module using a Framework I'm working on.
<?php
//  Author: Trabis
//  URL: http://www.xuups.com
//  E-Mail: lusopoemas@gmail.com
include dirname(dirname(dirname(__FILE__))) . '/mainfile.php';
include 
XOOPS_ROOT_PATH '/header.php';

if (!
xoops_load('bootstrap''Xuups')) {
    echo 
'Xuups Framework not found';
}

$criteria = new Xuups_Criteria_Compo(new Xuups_Criteria('id'1));
$criteria->add(new Xuups_Criteria('id'2), 'OR');
$criteria->add(new Xuups_Criteria('id'3), 'OR');
$render $criteria->renderWhere();
echo 
$render '<br>';

$helper Xuups_Module_Helper::getInstance('xteste');
$helper->setDebug(true);

//Echos module name, getModule() gets module object
echo $helper->getModule()->getVar('name') . '<br>';

$count $helper->getHandler('Post')->getCount();
if (
$count 5) {
    
$num $count 1;
    
$obj $helper->getHandler('Post')->create();
    
$obj->setVar('title'"Post number {$num});
    
$helper->getHandler('Post')->insert($obj);
}

$objs $helper->getHandler('Post')->getObjects($criteria);
foreach(
$objs as $obj) {
    echo 
$obj->getVar('title') . '<br>';
}

echo 
$helper->getConfig('config1') . '<br>';
echo 
$helper->getConfig('config2') . '<br>';
echo 
$helper->getConfig('config3') . '<br>'//trows an error on log cause config3 is missing


/**
* Alternative method to load language
* Xuups_Language::load('manifesto', 'xteste');
*/

$helper->loadLanguage('badmanifesto'); //trows error on log because language was not found

$helper->loadLanguage('manifesto');
echo 
_t('MA_XTESTE_HI') .'<br>';
echo 
_t('MA_XTESTE_GOODBYE') . '<br>';
echo 
_t('Something not translated yet!!!') . '<br>';


$helper Xuups_Module_Helper::getInstance('nomodulehere');
$helper->setDebug(true);
$helper->getModule(); //trows an error on log because module was not found

include XOOPS_ROOT_PATH '/footer.php';


I think we could all work together on making a module Framework. This code snippets are being very useful, thanks!



JulioNC

Quite a regular
Posted on: 2009/8/16 9:36
JulioNC
JulioNC (Show more)
Quite a regular
Posts: 239
Since: 2004/10/8
#5

Re: A singleton to access your data classes

Why isn't this feature part of Core 2.4?

I am not expert, but I think this will be named "model", and how to acces it could be nice with Registry or function to load you model (In this case php file into class/ ) like xoops_getmodulehandler() not as Helper.

"Helper" definition could be a snippet or "Utility functions" for specific topic that reduce the redundancy of code.

I will contact you