Jump to content

Recommended Posts

I have a questions regarding Singleton Pattern in this video:

 

Using the singleton pattern, isn't possible to have methods that aren't static? In this video it shows nothing but static methods. Also, after creating the class object like so:

 

$database = Database:Connect();

 

How would I go about using normal functions with that object? Say I had a query function. I can't do this:

 

$database->query();

 

So what would I do? :/ - Thanks for any help regarding this.

Link to comment
https://forums.phpfreaks.com/topic/260236-singleton-pattern/
Share on other sites

You can create the non static functions like normal.  Just you make the constructor and clone methods private so an external source can't create a new object.  Then you provide your own static method to build the object.

 

eg


class DB {
   private static $sConn;
   private function __construct(){ }
   private function __clone(){ }

   public static function Connect(){ 
      if (!self::$sConn){
        self::$sConn = new self;
      }
      return self::$sConn;
    }


    public function query($sql){
       echo $sql;
    }
}

 

Then your Connect static method returns the instance of the db class which you can then use to run the query method.

 

$db = DB::Connect();
$db->query('blah');

 

Link to comment
https://forums.phpfreaks.com/topic/260236-singleton-pattern/#findComment-1333832
Share on other sites

Thanks for that. I could've sworn I did something along those lines, but I probably messed up a step.

 

And I have one more quick question (if you have the time for it):

 

What's the point of singleton pattern? I mean, I know what it's purpose is and how it functions. But when would there ever be two of the same objects?

 

EDIT:

 

Also, using what you said - I get an error:

 

Fatal error: Using $this when not in object context in C:\wamp\www\OSREMAKE\OSRemakeCleaned\structure\base.php on line 35

 

My base.php

 

<?php
/*
* @INITIALIZER/BASE
* ~~~~~~~~~~~~
* @FILE DESCRIPTION: In simple terms: it "starts" the website, and acts as the heart of the website
* @LAST MODIFIED: March 27, 2012
* @INCLUDES: Database Class, Config
*/

class base
{
    private static $instance;
    public $db;
    
    /*
     * @METHOD  writeToFile
     * @DESC    writes the specified string to a specified file
     * @DESC    automatically creates file if it doesn't exist
     * 
     * @PARAM   string
     * @DESC    an array containing the lines/strings we want to write to the file
     */
    
    private function __construct() {}
    private function __clone() {}
    
    /*
     * SINGLETON PATTERN
     */
    public static function createInstance()
    {
        if(!self::$instance)
        {
            self::$instance = new self;
            $this->db = new database($db_host, $db_name, $db_user, $db_password);
        }
        
        return self::$instance;
    }
    
    public function writeToFile($file, array $string)
    {
        $file_handle = fopen($file, 'a');
        
        foreach($string as $string_to_write)
        {
            fwrite($string);
        }
        
        fclose($file_handle);
    }
}

?>

Link to comment
https://forums.phpfreaks.com/topic/260236-singleton-pattern/#findComment-1333835
Share on other sites

Since I can't edit my post, I'll add-on to my above post with this reply:

 

index.php

<?php
error_reporting(E_ALL ^ E_NOTICE);
/*
* @INDEX
* ~~~~~~~~~~~~
* @FILE DESCRIPTION: Homepage
* @LAST MODIFIED: April 3, 2012
*/

include('includes/config.php');
include('structure/base.php');
include('structure/database.php');

$base = base::createInstance();
$base->db->test();

?>

Link to comment
https://forums.phpfreaks.com/topic/260236-singleton-pattern/#findComment-1333837
Share on other sites

The point of the Singleton Pattern is to create a global that can only be created once.  By now alarms should be going off.  It's unfortunate that the Singleton is usually presented as the first pattern, because it's hardly ever a good idea to use it.  It's really an anti-pattern - something that looks neat and beneficial, but often winds up causing some form of damage it was meant to prevent.

 

Really, you'd be better off forgetting about the pattern and learning something useful like the Factory Method or Composite Pattern.  I'd say that 8/9 times out of 10, when someone thinks that using a Singleton is the best way to solve a problem, they should actually use Dependency Injection instead.

Link to comment
https://forums.phpfreaks.com/topic/260236-singleton-pattern/#findComment-1333914
Share on other sites

Thanks, I'll look into the above mentioned patterns and try to avoid using singleton.

 

As for your issue. You cannot use $this within a static method. This line:

 

$this->db = new database($db_host, $db_name, $db_user, $db_password);

 

belongs within your __construct().

 

=============

 

Ah.

 

I thought the singleton pattern doesn't allow the constructor to be used?

Link to comment
https://forums.phpfreaks.com/topic/260236-singleton-pattern/#findComment-1334157
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.