SitePoint Sponsor

User Tag List

Page 1 of 3 123 LastLast
Results 1 to 25 of 55
  1. #1
    SitePoint Addict
    Join Date
    Jan 2007
    Posts
    323
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    DB object in registry?

    Is there any opinion on whether the DB object should be included in the registry, its own object thats passed around, or as a singleton.

  2. #2
    simple tester McGruff's Avatar
    Join Date
    Sep 2003
    Location
    Glasgow
    Posts
    1,690
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I'd pass it around. I guess you're having problems doing that though?

  3. #3
    SitePoint Addict
    Join Date
    Jan 2007
    Posts
    323
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by McGruff View Post
    I'd pass it around. I guess you're having problems doing that though?
    No, but whenever I do if im also passing the registry object it seems im doubling up.

  4. #4
    SitePoint Addict
    Join Date
    Nov 2005
    Location
    Germany
    Posts
    235
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I'm starting to have mixed feelings about the Registry. As long as it solves my concurrency problems, it seems ok, but wait, let's put our config objects in there, our database handling and everything that has nothing to do with concurrency--it's simply too handy. On the other hand testing shows me that the registry starts living some secret inner life which is hard to control and debug once you put too many things in it.
    Am I paranoid?

    To answer atDev's question, I would pass it, too.

  5. #5
    SitePoint Wizard dreamscape's Avatar
    Join Date
    Aug 2005
    Posts
    1,080
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    FriB, a registry isn't a concurrency pattern. It's a basic pattern that serves as an object/service lookup. To quote POEAA, a registry is "A well-known object that other objects can use to find common objects and services."

    http://www.martinfowler.com/eaaCatalog/registry.html

    If the application architecture is quite simple, I would just pass the db object around.

    However, with some architectures, this gets quite silly to do as your db object ends up having to "jump through hoops" just to get to where it needs to be. In a case like that, there's no sense in being a fool about it. Use a registry, service locator, or similar.
    <.smarter.web.development.>
    PHP Stuff: Plexus | Chocolate (BDD Framework... coming soon)
    Graphite

  6. #6
    SitePoint Addict
    Join Date
    Jan 2007
    Posts
    323
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Would you make the registry a singleton or pass it?

  7. #7
    SitePoint Addict
    Join Date
    Nov 2005
    Location
    Germany
    Posts
    235
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by dreamscape View Post
    FriB, a registry isn't a concurrency pattern.
    Indeed, thanks for the hint, dreamscape. I'll have to read my POEAA again.
    [Anyway, I use a Registry to avoid having multiple copies of an instance. Not good? Sorry for going OT.]

  8. #8
    SitePoint Wizard silver trophy kyberfabrikken's Avatar
    Join Date
    Jun 2004
    Location
    Copenhagen, Denmark
    Posts
    6,157
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by atDev View Post
    No, but whenever I do if im also passing the registry object it seems im doubling up.
    I use the registry a lot, and as a golden rule, I tend to pass the most finegrained dependency around as possible. Sometimes that means passing the registry, but at other times, a class will only need a few dependencies (such as a db connection). In these cases, I will always prefer passing the actual dependency (the db connection) over passing the registry.

    Quote Originally Posted by atDev View Post
    Would you make the registry a singleton or pass it?
    If you make the registry a singleton, you have defied the purpose of the singleton in the first place, since the contained variables then becomes global in scope.

  9. #9
    SitePoint Addict
    Join Date
    Jan 2007
    Posts
    323
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by kyberfabrikken View Post
    I use the registry a lot, and as a golden rule, I tend to pass the most finegrained dependency around as possible. Sometimes that means passing the registry, but at other times, a class will only need a few dependencies (such as a db connection). In these cases, I will always prefer passing the actual dependency (the db connection) over passing the registry.



    If you make the registry a singleton, you have defied the purpose of the singleton in the first place, since the contained variables then becomes global in scope.
    When getting a class instance from the registry do we do so by reference? (php 4)

    $articles = &$registry->get('articles');

  10. #10
    SitePoint Addict
    Join Date
    Dec 2007
    Posts
    348
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by atDev View Post
    When getting a class instance from the registry do we do so by reference? (php 4)

    $articles = &$registry->get('articles');
    does $registry->get($var) return by reference? if so then I don't think you need to specify the & but I could be wrong.

  11. #11
    SitePoint Wizard silver trophy kyberfabrikken's Avatar
    Join Date
    Jun 2004
    Location
    Copenhagen, Denmark
    Posts
    6,157
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by old_iron View Post
    does $registry->get($var) return by reference? if so then I don't think you need to specify the & but I could be wrong.
    You need both in PHP4. But seriously, you need to upgrade -- php4 has been discontinued.

  12. #12
    SitePoint Addict
    Join Date
    Feb 2006
    Posts
    281
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I think you are wrong when you say it doubling everything up.

    This is how I do mine.

    PHP Code:
    <?php
    class Controller {
        
        
    /**
         * 
         * The data container.
         * 
         * @var array
         * 
         */        
        
    protected $data = array();
        
        
    /**
         * 
         * The registry object.
         * 
         * @var object
         * 
         */    
        
    protected $registry;

        
    /**
         * 
         * Sets the registry as a class attribute.
         * 
         * @param object $registry The registry object.
         *
         * @return void
         * 
         */    
        
    public function __construct(&$registry) {
            
    $this->registry =& $registry;
        }

        
    /**
         * 
         * Callback method for setting a attribute.
         * 
         * @param string $key The registry key.
         * @param mixed $value The registry value.
         *
         * @return void
         * 
         */        
        
    public function __set($key$value) {
            
    $this->registry->set($key$value);
        }

        
    /**
         * 
         * Callback method for getting a attribute.
         * 
         * @param string $key The registry key.
         *
         * @return object Returns object from the registry.
         * 
         */        
        
    public function __get($key) {
            return 
    $this->registry->get($key);
        }

        
    /**
         * 
         * Creates an action and returns it in an array.
         * 
         * @param string $action The registry object.
         *
         * @return array Returns the action array ready to be executed.
         * 
         */        
        
    protected function forward() {
            
    $args   func_get_args();
            
    $class  array_shift($args);
            
    $method array_shift($args);

            return new 
    Action($class$method$args);
        }

        
    /**
         * 
         * Redirects to another page.
         * 
         * @param string $url The registry object.
         *
         * @return void
         * 
         */        
        
    protected function redirect($url) {
            
    header('Location: ' $url);
            exit();
        }
        
        protected function 
    render($filename$data = array()) {
            
    $file DIR_VIEW 'template/' $filename '.tpl';
        
            if (
    file_exists($file)) {
                
    extract($data);
                
                  
    ob_start();
          
                  include(
    $file);
          
                  
    $content ob_get_contents();

                  
    ob_end_clean();

                  return 
    $content;
            } else {
                  exit(
    'Error: Could not load template ' $file '!');
            }        
        }
        
        protected function 
    getChild($child) {
            
    $file  DIR_CONTROLLER $child '.php';
            
    $class preg_replace('/[^a-zA-Z0-9]/''''Controller' $child);
            
            if (
    file_exists($file)) {
                include_once(
    $file);
                
                
    $controller = new $class($this->registry);
                
                return 
    $controller->execute();
            } else {
                exit(
    'Error: Could not load controller ' $child '!');
            }
        }
    }
    ?>
    It uses magic methods to get objects from the registry.

    PHP Code:
    <?php 
    class ControllerDefault extends Controller {
        function 
    index() {
            
    $this->load->language('common/default');
            
            
    $this->template->setTitle(sprintf($this->language->get('title'), $this->config->get('config_store')));
            
            
    $data['heading_title'] = sprintf($this->language->get('title'), $this->config->get('config_store'));
            
            
    $this->load->model('customer/customer');
            
            if (!
    $this->customer->isLogged()) {
                
    $data['text_greeting'] = sprintf($this->language->get('text_greeting'), $this->url->http('account/login'), $this->url->http('account/register'));
            } else {
                
    $data['text_greeting'] = sprintf($this->language->get('text_logged'), $this->customer->getFirstName());
            }

            
    $data['text_latest'] = $this->language->get('text_latest');

            
    $this->load->model('common/product');
            
    $this->load->model('cart/currency');
            
    $this->load->model('cart/tax');
            
            
    $this->load->library('image');

            
    $data['products'] = array();
            
            foreach (
    $this->product->getLatestProducts(16) as $result) {
                
    $width  $this->config->get('config_image_width');
                
    $height $this->config->get('config_image_height');
                
    /*
                //if () 
                $this->image->load(DIR_IMAGE . $result['filename']);
                $this->image->resize(100, 100);
                $this->image->save(DIR_IMAGE . 'cache/' . $result['filename']);
                */
                
    $data['products'][] = array(
                    
    'name'  => $result['name'],
                    
    'href'  => $this->url->http('product/product/product_id/' $result['product_id']),
                    
    'thumb' => HTTP_IMAGE 'cache/' $result['filename'],
                    
    'price' => $this->currency->format($this->tax->calculate($result['price'], $result['tax_class_id']))
                );
            }

            
    $this->response->setOutput($this->render('common/default'$data));
        }
    }
    ?>

  13. #13
    SitePoint Guru whisher's Avatar
    Join Date
    May 2006
    Location
    Kakiland
    Posts
    732
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by blueyon View Post
    I think you are wrong when you say it doubling everything up.

    This is how I do mine.

    PHP Code:
    <?php
    class Controller {
        
        
    /**
         * 
         * The data container.
         * 
         * @var array
         * 
         */        
        
    protected $data = array();
        
        
    /**
         * 
         * The registry object.
         * 
         * @var object
         * 
         */    
        
    protected $registry;

        
    /**
         * 
         * Sets the registry as a class attribute.
         * 
         * @param object $registry The registry object.
         *
         * @return void
         * 
         */    
        
    public function __construct(&$registry) {
            
    $this->registry =& $registry;
        }

        
    /**
         * 
         * Callback method for setting a attribute.
         * 
         * @param string $key The registry key.
         * @param mixed $value The registry value.
         *
         * @return void
         * 
         */        
        
    public function __set($key$value) {
            
    $this->registry->set($key$value);
        }

        
    /**
         * 
         * Callback method for getting a attribute.
         * 
         * @param string $key The registry key.
         *
         * @return object Returns object from the registry.
         * 
         */        
        
    public function __get($key) {
            return 
    $this->registry->get($key);
        }

        
    /**
         * 
         * Creates an action and returns it in an array.
         * 
         * @param string $action The registry object.
         *
         * @return array Returns the action array ready to be executed.
         * 
         */        
        
    protected function forward() {
            
    $args   func_get_args();
            
    $class  array_shift($args);
            
    $method array_shift($args);

            return new 
    Action($class$method$args);
        }

        
    /**
         * 
         * Redirects to another page.
         * 
         * @param string $url The registry object.
         *
         * @return void
         * 
         */        
        
    protected function redirect($url) {
            
    header('Location: ' $url);
            exit();
        }
        
        protected function 
    render($filename$data = array()) {
            
    $file DIR_VIEW 'template/' $filename '.tpl';
        
            if (
    file_exists($file)) {
                
    extract($data);
                
                  
    ob_start();
          
                  include(
    $file);
          
                  
    $content ob_get_contents();

                  
    ob_end_clean();

                  return 
    $content;
            } else {
                  exit(
    'Error: Could not load template ' $file '!');
            }        
        }
        
        protected function 
    getChild($child) {
            
    $file  DIR_CONTROLLER $child '.php';
            
    $class preg_replace('/[^a-zA-Z0-9]/''''Controller' $child);
            
            if (
    file_exists($file)) {
                include_once(
    $file);
                
                
    $controller = new $class($this->registry);
                
                return 
    $controller->execute();
            } else {
                exit(
    'Error: Could not load controller ' $child '!');
            }
        }
    }
    ?>
    Hum, it looks like a Konstrukt implementation

    Bye.

  14. #14
    SitePoint Wizard REMIYA's Avatar
    Join Date
    May 2005
    Posts
    1,351
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Now, I am using a global singleton factory using the magic methods, that generates the objects automaticly and I am very pleased. There are no scattered objects lying all arround. I have defined it in a function to be ready to use on the fly. Example:

    PHP Code:
     function pool(){
        return 
    Singleton_Factory::instance();

    Usage:

    PHP Code:
     // First usage
    $member pool()->member(1);
        
    // Creates new Member(1)
    // Second usage
    $member pool()->member(1);
        
    // Returnes the already generated instance

    // First usage
    $database pool()->database("host","user","pass");
        
    // Creates new Database("host","user","pass")

    // Second usage
    $database pool()->member("host","user","pass");
        
    // Returnes the already generated instance 
    NOTE: None of the Member or Database classes are singletons, so they can be easily extended further.

  15. #15
    . shoooo... silver trophy logic_earth's Avatar
    Join Date
    Oct 2005
    Location
    CA
    Posts
    9,013
    Mentioned
    8 Post(s)
    Tagged
    0 Thread(s)
    @blueyon
    Is there a reason why you use & in the constructor? I assume you are using PHP5 which made objects pass by reference by default. Unless I miss something you don't need & in this snippet.

    Code:
    public function __construct(&$registry) { 
        $this->registry =& $registry; 
    }
    

    Logic without the fatal effects.
    All code snippets are licensed under WTFPL.


  16. #16
    SitePoint Addict
    Join Date
    Jan 2007
    Posts
    323
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    What would a generic registry look like as far as using references in PHP5 then?

  17. #17
    . shoooo... silver trophy logic_earth's Avatar
    Join Date
    Oct 2005
    Location
    CA
    Posts
    9,013
    Mentioned
    8 Post(s)
    Tagged
    0 Thread(s)
    Bare bones registry:
    PHP Code:
    <?php

    class Registry
    {
        protected static 
    $index = array();

        public static function 
    add $name$object$overwrite false )
        {
            if ( isset( 
    self::$index$name ] ) && !$overwrite ) {
                throw new 
    Exception'Cannot overwrite existing object.' );
                return 
    false;
            }

            
    self::$index$name ] = $object;
            return 
    true;
        }

        public static function 
    call $name )
        {
            if ( !isset( 
    self::$index$name ] ) ) {
                throw new 
    Exception'Cannot call non-existing object.' );
                return 
    false;
            }

            return 
    self::$index$name ];
        }
    }

    Registry::add'database', new DB() );
    Registry::add'something', new Something() );

    $db Registry:call'database' );
    $db->fetch();

    $s Registry:call'something' )->method();
    Logic without the fatal effects.
    All code snippets are licensed under WTFPL.


  18. #18
    SitePoint Wizard silver trophy kyberfabrikken's Avatar
    Join Date
    Jun 2004
    Location
    Copenhagen, Denmark
    Posts
    6,157
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Even barer:
    PHP Code:
    $GLOBALS['database'] = new DB();
    $GLOBALS['something'] = new Something();

    $db $GLOBALS['database'];
    $db->fetch();

    $s $GLOBALS['something']->method(); 
    I'll advise that you use a locally scoped variable instead, if you use a registry.

  19. #19
    . shoooo... silver trophy logic_earth's Avatar
    Join Date
    Oct 2005
    Location
    CA
    Posts
    9,013
    Mentioned
    8 Post(s)
    Tagged
    0 Thread(s)
    Just to note the above post, be very careful with $GLOBALS you can overwrite other variables very easy.

    PHP Code:
    <?php

    $GLOBALS
    ['cat'] = 'mew';

    var_dump$GLOBALS );

    var_dump$cat );

    $cat 'arf';

    var_dump$GLOBALS );
    Logic without the fatal effects.
    All code snippets are licensed under WTFPL.


  20. #20
    SitePoint Wizard REMIYA's Avatar
    Join Date
    May 2005
    Posts
    1,351
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by logic_earth View Post
    Bare bones registry
    Instead of overwrite, it will be better to have additional methods:

    exists,overwrite
    PHP Code:
    if(Registry::exists(o))Registry::overwrite(o); 

  21. #21
    SitePoint Evangelist ghurtado's Avatar
    Join Date
    Sep 2003
    Location
    Wixom, Michigan
    Posts
    591
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Why would it be better, Remiya? Logic's implementation achieves the same results with two less methods than yours. Personally, I think simpler is better.
    Garcia

  22. #22
    SitePoint Wizard REMIYA's Avatar
    Join Date
    May 2005
    Posts
    1,351
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by ghurtado View Post
    Why would it be better, Remiya? Logic's implementation achieves the same results with two less methods than yours. Personally, I think simpler is better.
    At some point code readability surpasses, writing less. When you see overwrite you know, that you overwrite an object. If there is no overwrite, then the object is the same.
    Readability is always an issue, when you go back to some of your projects after a while. And this moment always comes and takes us aback. ("Was it me writing this? What am I doing this for?")

  23. #23
    . shoooo... silver trophy logic_earth's Avatar
    Join Date
    Oct 2005
    Location
    CA
    Posts
    9,013
    Mentioned
    8 Post(s)
    Tagged
    0 Thread(s)
    Well since you what a more complete Registry... (not perfect, far from it.)
    Handles more then just objects of course.



    Personally I would use something like Zend_Registry.


    PHP Code:
    $test = new stdClass;
    $test->dog 'goes arf';
     
    Registry::add'cat''goes mew' );
    Registry::add'test'$test );
     
    Registry::debug_dump();
     
    var_dumpRegistry::call'test' )->dog ); 
    PHP Code:
    <?php
     
    class Registry
    {
        static protected 
    $_index = array();
        static protected 
    $_data  = array();
     
        
    #---------------------------------------------------------------------------
     
        
    static protected function _fetch_key $name )
        {
            
    $name strtolowertrim$name ) );
            if ( isset( 
    self::$_index$name ] ) ) {
                return 
    self::$_index$name ];
            }
     
            return 
    false;
        }
     
        static public function 
    exist $name )
        {
            return 
    self::_fetch_key$name ) !== false true false;
        }
     
        
    #---------------------------------------------------------------------------
     
        
    static protected function _add_object $name$object$overwrite )
        {
            
    $key  self::_fetch_key$name );
            
    $hash 'object::' spl_object_hash$object );
     
            if ( 
    $key !== false && $key !== $hash ) {
     
                if ( !
    $overwrite ) {
                    throw new 
    Exception'Cannot overwrite existing object without explicit permission.' );
                    return 
    false;
                }
     
            }
     
            if ( 
    $key !== $hash ) { self::$_data$hash ] = $object; }
            
    self::$_index$name ] = $hash;
     
            return 
    true;
        }
     
        static public function 
    add $name$data$overwrite false )
        {
            
    $name strtolowertrim$name ) );
     
            if ( 
    is_object$data ) ) {
                return 
    self::_add_object$name$data$overwrite );
            }
     
            
    $key  self::_fetch_key$name );
     
            if ( !
    $overwrite && $key !== false ) {
                throw new 
    Exception'Cannot overwrite existing data without explicit permission.' );
                return 
    false;
            }
     
            
    self::$_index$name ] = $data;
            return 
    true;
        }
     
        static public function 
    set $name$object$overwrite false )
        {
            return 
    self::add$name$object$overwrite );
        }
     
        static public function 
    overwrite $name$object )
        {
            return 
    self::add$name$objecttrue );
        }
     
        
    #---------------------------------------------------------------------------
     
        
    static public function call $name )
        {
            
    $key self::_fetch_key$name );
            if ( 
    strpos$key'object::' ) !== false ) {
                return 
    self::$_data$key ];
            }
     
            return 
    $key;
        }
     
        static public function 
    get $name )
        {
            return 
    self::call$name );
        }
     
        
    #---------------------------------------------------------------------------
     
        
    static public function remove $name )
        {
            
    $name strtolowertrim$name ) );
            
    $key  self::_fetch_key$name );
     
            if ( 
    strpos$key'object::' ) !== false ) {
                unset( 
    self::$_data$key ] );
            }
     
            unset( 
    self::$_index$name ] );
            return 
    true;
        }
     
        
    #---------------------------------------------------------------------------
     
        
    static public function debug_dump ()
        {
            
    var_dumpself::$_index );
            
    var_dumpself::$_data );
        }
    }
    Logic without the fatal effects.
    All code snippets are licensed under WTFPL.


  24. #24
    SitePoint Addict
    Join Date
    Feb 2006
    Posts
    281
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by logic_earth View Post
    @blueyon
    Is there a reason why you use & in the constructor? I assume you are using PHP5 which made objects pass by reference by default. Unless I miss something you don't need & in this snippet.

    Code:
    public function __construct(&$registry) { 
        $this->registry =& $registry; 
    }
    


    I think the & is still required for this part of the code.

    I have checked the PHP5 documentation and as far as I know refrences are only pasted by default when returning a object from a method or function.

    Can you please give me details of where to use references?

  25. #25
    . shoooo... silver trophy logic_earth's Avatar
    Join Date
    Oct 2005
    Location
    CA
    Posts
    9,013
    Mentioned
    8 Post(s)
    Tagged
    0 Thread(s)
    Made a little test to see how PHP5 (5.2.5) handles it. Conclusion & not required.

    PHP Code:
    <?php

    class Test_Object
    {
        public 
    $test;

        public function 
    __construct $test )
        {
            
    $this->test $test;
        }
    }

    $std = new StdClass;
    $std->dog 'bark';

    $test = new Test_Object$std );

    var_dump$test );

    $std->cat 'meow';

    var_dump$test );
    Logic without the fatal effects.
    All code snippets are licensed under WTFPL.



Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •