5 Replies - 9844 Views - Last Post: 13 April 2012 - 09:17 AM

#1 creativecoding  Icon User is offline

  • Hash != Encryption
  • member icon


Reputation: 928
  • View blog
  • Posts: 3,212
  • Joined: 19-January 10

Object Oriented + Sharing classes

Post icon  Posted 07 April 2012 - 01:19 AM

So in OO design, you have multiple classes for multiple purposes. A database class, a class for your user, a class for registering, etc etc. But what if you need to share something like the database class between all of these other classes? Is there any way to do that simply without including and using new class every time I need it?

This post has been edited by codeprada: 08 April 2012 - 11:08 AM

Is This A Good Question/Topic? 1
  • +

Replies To: Object Oriented + Sharing classes

#2 Atli  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3730
  • View blog
  • Posts: 6,017
  • Joined: 08-June 10

Re: Object Oriented + Sharing classes

Posted 07 April 2012 - 01:59 AM

*
POPULAR

That sounds like a perfect situation for the Singleton Pattern.

As an example, this is a compact version of what I usually do for my database connections:
class Database
{
	/** @var PDO The shared database link. */
	protected static $dbLink;

	/**
	 * Returns an open PDO object.
	 * @return PDO
	 */
	public static function get()
	{
		if(self::$dbLink == null)
		{
			$dns = Config::get('db.adapter') . ':host=' . Config::get('db.host') . ';dbname=' . Config::get('db.dbname');
			self::$dbLink = new \PDO($dns, Config::get('db.username'), Config::get('db.password'));

			if (Config::get('db.adapter') == "mysql")
			{
				$encoding = strtoupper(Config::get('db.charset'));
				self::$dbLink->exec("SET NAMES '{$encoding}'");
			}
		}
		return self::$dbLink;
	}

	/*
	 * The class is not meant to be instantiated so the constructor
	 * and clone methods are hidden. (You could also just make it
	 * abstract, but I like this way better :P/>)
	 */
	private function __construct() {
		return false;
	}
	private function __clone() {
		return self::get();
	}
}


Then wherever I need access to the database, I just do:
$db = Database::get();


Was This Post Helpful? 6
  • +
  • -

#3 codeprada  Icon User is offline

  • Changed Man With Different Priorities
  • member icon

Reputation: 948
  • View blog
  • Posts: 2,357
  • Joined: 15-February 11

Re: Object Oriented + Sharing classes

Posted 08 April 2012 - 11:15 AM

Atli's post gave me some new insight. Most people, myself included, settle for the simple include method of sharing database credentials and connections across their application but the method above is much more flexible.
Was This Post Helpful? 0
  • +
  • -

#4 hiddenghost  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 39
  • View blog
  • Posts: 621
  • Joined: 15-December 09

Re: Object Oriented + Sharing classes

Posted 08 April 2012 - 09:31 PM

I did something similar to what Atli did, but with anonymous functions.

I'm afraid to show it here, but I'll tell you a little.

It has a top level array function named 'newPDO' as the key that accepts parameters of sql access info. The pdo object is passed through the use() as a closure into 'newPDO'.

The connection is made inside 'newPDO'. Then it's propagated to the inner functions through closure again.

An array of common functions like select, insert, update are returned from 'newPDO' when 'newPDO' is assigned to a variable.

The returned array has appropriately named keys for types of inputs or selects on the db.

There are two selects.
One that outputs by column name and one that outputs by row index.

The one that outputs by column name is the cool one because it makes the resultant array look like the db fields. It has some funky code in it.

There's a multi-input function too which does multiple types of input at any column amount. Just insert an array of inserts and updates and it goes.

It's all prepared statements, though that might be over doing it, it makes it easy to specify input to the functions for inserts, and selects.

I guess that's a little bit more than a connection.

It's my style. I like it.
The function(s) uses closure like crazy.
Was This Post Helpful? 0
  • +
  • -

#5 hiddenghost  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 39
  • View blog
  • Posts: 621
  • Joined: 15-December 09

Re: Object Oriented + Sharing classes

Posted 08 April 2012 - 09:38 PM

Actually I was a little off on my description.

This is kinda how I did it.
$connector['newPDO'] = function($conn_array = array()){
    try {
    $dbUse = new PDO("mysql:host=localhost;dbname=".$conn_array[0], $conn_array[1], $conn_array[2]);
    } catch( PDOException $err ) { echo "<br>PDO error: ".$err->getMessage()."<br>"; die(); }

    //db action arrays
    $dbIs['select'] = function($query) use($dbUse){};
    $dbIs['input'] ... and more functions

    return $dbIs;
};



The $connector function can be called once and all the inner function array that's returned has access.

I know. It's a little weird. :)

This post has been edited by hiddenghost: 08 April 2012 - 09:48 PM

Was This Post Helpful? 0
  • +
  • -

#6 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 3576
  • View blog
  • Posts: 10,439
  • Joined: 08-June 10

Re: Object Oriented + Sharing classes

Posted 13 April 2012 - 09:17 AM

View Posthiddenghost, on 09 April 2012 - 06:38 AM, said:

I know. It's a little weird. :)

yepp. die() and Exceptions do not get along well.

I mean, why the he** do you die() there? you intentionally break your output (usually HTML) and can do nothing to clean up. basic rule for Exceptions: catch() where you can handle the error! (and that is at least in the calling function, if not further).
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1