Singleton

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • [Mystic]

    Singleton

    I was just wondering something about this.

    I wanted to do something similar, like having a mysql class that there can
    only be one of. The purpose of this was not to have hundereds to mysql
    connections open, and also to track how many queries are being sent/second.

    When creating the singleton, I assume you use this syntax:

    $var = &new singelton;

    However, in the class, how can you check to make sure there has not been
    another class created under a different var?

    My way of doing it would have been to make a static var in the __construct
    class, checking if this has been registered as a var or not. If no, create
    class, otherwise exit class.

    Would this work? Or is there a better way of doing it?

    Thanks.


  • porneL

    #2
    Re: Singleton

    > My way of doing it would have been to make a static var in the [color=blue]
    > __construct
    > class, checking if this has been registered as a var or not. If no,
    > create
    > class, otherwise exit class.[/color]

    You can't prevent construction in constructor.

    $singleton = &Class::obtainI nstance();

    obtainInstance should be static method, which returns existing
    instance (from static var) or creates new one.

    AFAIK in PHP it is not possible to make general base class for singletons
    - you need to, but cannot know the name of inheriting class that uses
    function of the base class.

    --
    * html {redirect-to: url(http://browsehappy.pl) ;}

    Comment

    • Andy Hassall

      #3
      Re: Singleton

      On Wed, 19 Jan 2005 12:58:37 +1300, "[Mystic]" <screwuspamme r> wrote:
      [color=blue]
      >I was just wondering something about this.
      >
      >I wanted to do something similar, like having a mysql class that there can
      >only be one of. The purpose of this was not to have hundereds to mysql
      >connections open, and also to track how many queries are being sent/second.
      >
      >When creating the singleton, I assume you use this syntax:
      >
      >$var = &new singelton;
      >
      >However, in the class, how can you check to make sure there has not been
      >another class created under a different var?
      >
      >My way of doing it would have been to make a static var in the __construct
      >class, checking if this has been registered as a var or not. If no, create
      >class, otherwise exit class.
      >
      >Would this work? Or is there a better way of doing it?[/color]

      If you mean "return the previously created object" where you said "exit class"
      then yes, that's pretty much the standard way of creating a singleton. In
      multithreaded languages there's a bit more to it, to stop a race condition
      creating two instances concurrently, but that's not a problem in PHP.

      "php singleton" on Google yields some useful looking hits.

      --
      Andy Hassall / <andy@andyh.co. uk> / <http://www.andyh.co.uk >
      <http://www.andyhsoftwa re.co.uk/space> Space: disk usage analysis tool

      Comment

      • Tim Van Wassenhove

        #4
        Re: Singleton

        On 2005-01-18, [Mystic] <screwuspamme r> wrote:[color=blue]
        > I was just wondering something about this.
        >
        > I wanted to do something similar, like having a mysql class that there can
        > only be one of. The purpose of this was not to have hundereds to mysql
        > connections open, and also to track how many queries are being sent/second.
        >
        > When creating the singleton, I assume you use this syntax:
        >
        > $var = &new singelton;
        >
        > However, in the class, how can you check to make sure there has not been
        > another class created under a different var?
        >
        > My way of doing it would have been to make a static var in the __construct
        > class, checking if this has been registered as a var or not. If no, create
        > class, otherwise exit class.
        >
        > Would this work? Or is there a better way of doing it?[/color]

        Only a couple of things to get you started (php5)

        - make the constructor private
        - make a public method getInstance that provides the static instance of
        the class (if that instance == null -> call constructor...)
        - override the __clone function... (might encounter a problem here.....)

        --
        Met vriendelijke groeten,
        Tim Van Wassenhove <http://www.timvw.info>

        Comment

        • [Mystic]

          #5
          Re: Singleton

          Thanks all of you,

          Very helpful information.


          Comment

          • [Mystic]

            #6
            Re: Singleton

            One last thing,

            How can you call a classes function, before you have even created an object
            that uses that class?

            IE:

            class::GetInsta nce();



            Comment

            • [Mystic]

              #7
              Re: Singleton

              This is what I have so far:

              class database {

              private function __construct($ca lled_from_getin stance = false) {
              if (!$called_from_ getinstance)
              echo "Fatal error has occured. Tried to recreate database() class";
              }

              public function &getInstane( ) {
              static $database_objec t; // reference object

              if (!is_object($da tabase))
              $database_objec t = new database(true); // create new object

              return $database_objec t; // return address of object
              }
              }

              $test = &database::getI nstane(); // get static instance of class
              ?>

              Can anyone see any errors in this?

              Im getting the following:
              Debug Strict (PHP 5): C:\Projects\ixo n.co.nz\include s\classes\mysql .class
              line 26 - Non-static method database::getIn stane() should not be called
              statically



              Comment

              • Tim Van Wassenhove

                #8
                Re: Singleton

                On 2005-01-19, [Mystic] <screwuspamme r> wrote:
                [snip singleton code]



                <?php
                error_reporting (E_ALL);

                class Singleton
                {
                private static $singleton;

                private function __construct()
                {
                mysql_connect(' localhost', 'timvw', 'tvw123');
                mysql_select_db ('timvw');
                }

                public static function getInstance()
                {
                if (self::$singlet on == null)
                {
                self::$singleto n = new Singleton;
                }
                return self::$singleto n;
                }

                public function __clone()
                {
                trigger_error(' Clone is not allowed.', E_USER_ERROR);
                }
                }

                $singleton = Singleton::getI nstance();
                $evil = clone($singleto n);
                ?>



                --
                Met vriendelijke groeten,
                Tim Van Wassenhove <http://www.timvw.info>

                Comment

                • Tim Van Wassenhove

                  #9
                  Re: Singleton

                  On 2005-01-19, [Mystic] <screwuspamme r> wrote:[color=blue]
                  > This is what I have so far:
                  >
                  > class database {
                  >
                  > private function __construct($ca lled_from_getin stance = false) {
                  > if (!$called_from_ getinstance)
                  > echo "Fatal error has occured. Tried to recreate database() class";
                  > }
                  >
                  > public function &getInstane( ) {
                  > static $database_objec t; // reference object
                  >
                  > if (!is_object($da tabase))
                  > $database_objec t = new database(true); // create new object
                  >
                  > return $database_objec t; // return address of object
                  > }
                  > }
                  >
                  > $test = &database::getI nstane(); // get static instance of class
                  > ?>
                  >
                  > Can anyone see any errors in this?
                  >
                  > Im getting the following:
                  > Debug Strict (PHP 5): C:\Projects\ixo n.co.nz\include s\classes\mysql .class
                  > line 26 - Non-static method database::getIn stane() should not be called
                  > statically[/color]

                  You should make the getInstance function static.....


                  <?php

                  error_reporting (E_ALL);

                  class Singleton
                  {
                  private static $singleton;

                  private function __construct()
                  {
                  mysql_connect(' localhost', 'timvw', 'xxxxxx');
                  mysql_select_db ('timvw');
                  }

                  public static function getInstance()
                  {
                  if (self::$singlet on == null)
                  {
                  self::$singleto n = new Singleton;
                  }
                  return self::$singleto n;
                  }

                  public function __clone()
                  {
                  trigger_error(' Clone is not allowed.', E_USER_ERROR);
                  }
                  }

                  $singleton = Singleton::getI nstance();
                  $evil = clone($singleto n);
                  ?>




                  --
                  Met vriendelijke groeten,
                  Tim Van Wassenhove <http://www.timvw.info>

                  Comment

                  • NC

                    #10
                    Re: Singleton

                    [Mystic] wrote:[color=blue]
                    >
                    > I wanted to do something similar, like having a mysql class
                    > that there can only be one of. The purpose of this was not
                    > to have hundereds to mysql connections open,[/color]

                    Well, let's start by reading PHP documentation:

                    If a second call is made to mysql_connect() with the same
                    arguments, no new link will be established, but instead,
                    the link identifier of the already opened link will be
                    returned.



                    So there's no need to use singletons for this purpose. MySQL
                    is capable of doing it on its own.

                    Cheers,
                    NC

                    Comment

                    • [Mystic]

                      #11
                      Re: Singleton


                      "Tim Van Wassenhove" <timvw@users.so urceforge.net> wrote in message
                      news:356373F4hg 77aU4@individua l.net...[color=blue]
                      > On 2005-01-19, [Mystic] <screwuspamme r> wrote:[color=green]
                      > > This is what I have so far:
                      > >
                      > > class database {
                      > >
                      > > private function __construct($ca lled_from_getin stance = false) {
                      > > if (!$called_from_ getinstance)
                      > > echo "Fatal error has occured. Tried to recreate database() class";
                      > > }
                      > >
                      > > public function &getInstane( ) {
                      > > static $database_objec t; // reference object
                      > >
                      > > if (!is_object($da tabase))
                      > > $database_objec t = new database(true); // create new object
                      > >
                      > > return $database_objec t; // return address of object
                      > > }
                      > > }
                      > >
                      > > $test = &database::getI nstane(); // get static instance of class
                      > > ?>
                      > >
                      > > Can anyone see any errors in this?
                      > >
                      > > Im getting the following:
                      > > Debug Strict (PHP 5):[/color][/color]
                      C:\Projects\ixo n.co.nz\include s\classes\mysql .class[color=blue][color=green]
                      > > line 26 - Non-static method database::getIn stane() should not be called
                      > > statically[/color]
                      >
                      > You should make the getInstance function static.....
                      >
                      >
                      > <?php
                      >
                      > error_reporting (E_ALL);
                      >
                      > class Singleton
                      > {
                      > private static $singleton;
                      >
                      > private function __construct()
                      > {
                      > mysql_connect(' localhost', 'timvw', 'xxxxxx');
                      > mysql_select_db ('timvw');
                      > }
                      >
                      > public static function getInstance()
                      > {
                      > if (self::$singlet on == null)
                      > {
                      > self::$singleto n = new Singleton;
                      > }
                      > return self::$singleto n;
                      > }
                      >
                      > public function __clone()
                      > {
                      > trigger_error(' Clone is not allowed.', E_USER_ERROR);
                      > }
                      > }
                      >
                      > $singleton = Singleton::getI nstance();
                      > $evil = clone($singleto n);
                      > ?>
                      >
                      >
                      >
                      >
                      > --
                      > Met vriendelijke groeten,
                      > Tim Van Wassenhove <http://www.timvw.info>[/color]

                      Thanks heaps.


                      Comment

                      • [Mystic]

                        #12
                        Re: Singleton


                        "NC" <nc@iname.com > wrote in message
                        news:1106114400 .879037.8890@c1 3g2000cwb.googl egroups.com...[color=blue]
                        > [Mystic] wrote:[color=green]
                        > >
                        > > I wanted to do something similar, like having a mysql class
                        > > that there can only be one of. The purpose of this was not
                        > > to have hundereds to mysql connections open,[/color]
                        >
                        > Well, let's start by reading PHP documentation:
                        >
                        > If a second call is made to mysql_connect() with the same
                        > arguments, no new link will be established, but instead,
                        > the link identifier of the already opened link will be
                        > returned.
                        >
                        > http://www.php.net/manual/en/function.mysql-connect.php
                        >
                        > So there's no need to use singletons for this purpose. MySQL
                        > is capable of doing it on its own.
                        >
                        > Cheers,
                        > NC
                        >[/color]

                        Thanks


                        Comment

                        Working...