Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
  Advanced Search
  HOME    TRACKER    PHP


SuperbHosting.net have generously sponsored dedicated servers to ensure a reliable and scalable dedicated hosting solution for BigResource.com.





Real World Singleton Class Example?


Anybody can show me real world singleton class example?
Something that works (is implemented) as part of working solution.
Does it make sense to create database handler class that way?




View Complete Forum Thread with Replies

Related Forum Messages:
Singleton Class Scope Problem
On my site I want to make two classes. One that can be instantiated
normally and one with extended functionality that can only be
instantiated once. The Singleton pattern thus seems like a logical
choice for the second class. However, I would like the second
(singleton) class to extend the first. Something like this:

<?php
class User
{
public function __construct ()
{
doSomething();
}
}

class Member extends User
{
private static $instance = NULL;
public static function getInstance ()
{
if (self::$instance === NULL)
self::$instance = new Member;
return self::$instance;
}

private function __construct () {}
private function __clone () {}
}
?>
But this gives me the following error:
Fatal error: Access level to Member::__construct() must be public (as
in class User) in class.member.php on line 6

But I don't want the constructor to be public, because I want it to be
impossible to create more than one instance.

View Replies !
A Real Challenge For Real PHP Programmers
<?php
/*
A challenge to every PHP programmer.The one who's gonna solve this
problem would be deemed as

PSP(PHP Supreme Programmer).The problem is this : You have to write a
script that displays a list of

categories and subcategorieslike this one:

<select name="category">
<option value="1">Main</option>
<option value="2">Main > Computers</option>
<option value="4">Main > Computers > Hardware </option>
<option value="8">Main > Computers > Hardware > PC</option>
<option value="7">Main > Computers > Hardware > Mac</option>
<option value="9">Main > Computers > Hardware > Atari</option>
<option value="11">Main > Computers > Hardware > PC > History of
Pc</option>
<option value="">etc...</option>
</select>

The categories and subcategories details are stored in these two
tables in a MySQL database.
-categories : the categories names and ids.
-cat_relations : the relations between categories.It shows which
subcategory belongs to which category.
The belongings between categories can go very deep and the number of
categories is unlimited. This script will create the two tables and
fill them with sample data. All you need to do is to change the four
variables below. You can send the script back to this email :
yasbergy@yahoo.com.
*/

//Here starts the script. Please change the values of these variables
to fit your settings
$user = "prospective_PSP";
$database = "db";
$server = "localhost" ;
$pwd = "" ;
//Connection to the database that you created
mysql_connect($server,$user,$pwd) ;
mysql_select_db($database);
//Creation of the two tables : categories and cat_relations
$categories = " CREATE TABLE `categories` (`id` INT not null
AUTO_INCREMENT, `name` VARCHAR(100) not null , PRIMARY KEY (`id`),
INDEX (`id`), UNIQUE (`id`)) comment = 'The categories details' ";
mysql_query($categories) ;
$cat_relations = "CREATE TABLE `cat_relations` (`id` INT not null
AUTO_INCREMENT, `daughter_id` INT not null, `mother_id` INT not null ,
PRIMARY KEY (`id`), INDEX (`id`), UNIQUE (`id`)) comment = 'Which
category is the daughter of which category'";
mysql_query($cat_relations) ;

//Filling the two tables with sample data
$cats = array('Main','Computers','Countries','Hardware','S oftware','Programming
languages','Mac','PC','Atari','Winamp','History of the
PC','IBM','Components','High
level','USA','NYC','LA','Manhattan','India','Winzi p');
for ($i=0;$i<count($cats);$i++){
$sql = mysql_query("insert into categories (name)
values('".$cats[$i]."')");
}
mysql_query("insert into cat_relations (daughter_id,mother_id) values
(2,1),(3,1),(4,2),(5,2),(6,2),(7,4),(8,4),(9,4),(1 1,8),(12,8),(13,8),(10,5),(20,5),(14,6),(15,3),(16

,15),(17,15),(18,16),(19,3)");
//Now you can have a look on them through phpMyAdmin
?>

View Replies !
Singleton
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.

View Replies !
Error From Hello-World Program
I wrote a simple "Hello World" program, but
I got a warning as following

Warning: Failed opening '/home/ma/b/dhou/public_html/index.php'
for inclusion (include _path='.:/usr/local/lib/php') in
Unknown on line 0.

It was my mistake that I didn't open the permission 644 for my
index.php. But what I don't understand is the error message,
would anybody please explain that "for inclusion..." part of
the warning message to me?? Why the file permission has something
to do with the inclusion of a library?


View Replies !
Zip Code Database For The Whole World?
I know there are about 43,000+ for the USA alone, but it'd be nice to have the whole world haha. For now I want to use it for a super accurate zip code verification hahaha. Later though I will use it for latitude, longitude look ups though.

View Replies !
World Location Script
Id like to do something where people can enter their name and location and it shows something like a world map. with a mark for the person's name @ their location. Kind of like you see in SMALL truck stop resturants when ur traveling.

View Replies !
The Singleton Pattern In PHP 5
To add to my growing library of Design Patterns in PHP 5 I have
written what I think is a good example of the Singleton Pattern.

In the classic singleton pattern an object will distribute one and
only one instance of itself. This can be useful for the sharing of
resources such as a single db or network connection.

A variation, sometimes called a multiton, would distribute a limited
number of instances of itself. Useful, say if you had a limited
number of db connections to share.

View Replies !
PHP Singleton Function
in http://hk.php.net/manual/en/language.oop5.patterns.php, it mentions
the use of "Singleton"function. e.g.

//*********************
public static function singleton()
{
if (!isset(self::$instance)) {
$c = __CLASS__;
self::$instance = new $c;
}

return self::$instance;
}
//*********************

if this instance use a lot of memory, would it be better if i use
reference?

e.g.

//*********************
public static function &singleton()
{
if (!isset(self::$instance)) {
$c = __CLASS__;
self::$instance = new $c;
}

return self::$instance;
}
//*********************

View Replies !
RSS Feed For World Time Zones
I am working on different country projects, where the delivery time of the project will be saved on their respective country timings.We need to display the time in IST time zone accordingly. I need to calculate the time difference between different india and other countries. For that is there any RSS live feed available to get the time difference between two countries. (dynamic values of the time difference according to the countries).

View Replies !
Protecting A World Writtable Folder
I create a photo uploading system and had to make the destination folder world writtable folder. How do I prevent people from uploading their own files to this folder?

View Replies !
Grab Time From World Clock
I need to grab times for few cities from world clock site. Not sure how I can do that.
So lets say I want to grab New York time from that site. Not the weekday name. just New yorks time. and show it on my site. How would I do that.

View Replies !
Output The Time In Various Cities Around The World
I need some php to output the time in various cities around the world (London, Hong Kong, Bangkok etc), and automatically take account for daylight saving times etc...

Any easy ways to do this? Obviously you can't set the offset manually as it changes from time to time...

View Replies !
Constructors With The Singleton Pattern?
I would like my script to connect to a MySQL server the first time the object is initialized. Since I'll be using the Singleton pattern for my DB class, I was wondering how to emulate a constructor with it.

View Replies !
Singleton Pattern Not Working
I'm trying to create a singleton (only one instance of a class), but
this doesn't work, can anyone explain this?

<code>

function &get_instance()
{
static $instance;
if (! isset($instance))
{
echo "test";
$instance =& new Foo();
}

return $instance;
}

</code>

It get called like this: $bar =& Foo::get_instance();

I've seen examples on the web, saying this should work. What am I doing
wrong?

View Replies !
Private Constructor (singleton)
I am trying to make a class just for connecting to the MySQL and I want to make it a singleton because only one connection should ever be needed at a time. Code:

View Replies !
PHP Can Only Upload File Into A World-writeable Folder?
Every time I try to upload a file, it works fine until I use move_uploaded_file() to try to place it in its destination, then I get an error to the effect of:

Warning: Unable to create '/path/to/file.ext': Permission denied in /path/to/script.php on line XX

This error goes away when I make the folder I'm trying to move the file into a world-writeable one.

Has it been other peoples' experience that making the upload folder world-writeable is the only way to move new uploaded files into it?

View Replies !
Racking My Brains Over The Simplest Question In The World
Put simply I have an XML file such as:

<page>
<door>brown</door>
<roof>pink</roof>
</page>

Using the DOM functions in PHP, how would I test to see if the the
element <door> is empty?

View Replies !
(OT) Where To Download World List Of Countries And Their Cities?
I need to populate a database with a list of countries of the world,
along with the cities (cities dosent need to be an extensive list). Does
anyone know where I can download such a file? - to save me having to
manually create such a file from (possibly various sources)?

View Replies !
Singleton Design Pattern Relveance In PHP
Since the webserver loads a PHP script every time a request is issued
from a client, it seems that Singletons are unnessesary in PHP?, since
each time an object is invoked, it is (guaranteed?) to be the only
instance - at least for that thread that is handling the request ? No ?

View Replies !
-> PHP4 Singleton Implementation Question <-
I'm trying to implement a singleton in PHP4 but it doesn't seem to
work. The object is recreated each time I call it.

The goal of the class is to keep a variable up to date.
It's used to display a database content, 25 rows at a time.
The singleton keeps track of the current starting row and
increases it or decreases it by 25 depending on the user action
(pressing a Next or Prev button).
Those buttons are submit buttons calling the current form itself.

But each time I re-enter that form, the singleton variable is created
again and therefore the currentRow variable reinitilized.

Here is the code for the class called Welcome:
---------------------------------------------
class Welcome {
var $offsetRows = 25;
var $currentRow ;
// ************************************************** ********
// INSTANCE function to instanciate this class only once
// ************************************************** ********
function &getInstance() {
static $instance ;
if( !$instance ) {
$instance = new Welcome() ;
}
return $instance ;
}
// **************************************************
// CONSTRUCT function called when object is created
// **************************************************
function Welcome() {
$this->currentRow = 0 ;
$this->offsetRows = 25 ;
}
// **************************************************
// SHOWRECORDS
// Displays the actual table with info in rows.
// **************************************************
function showRecords() {
// my table display code here using $this->currentRow
}

// **************************************************
// NEXTRECORDS
// Displays the next nn offset records
// **************************************************
function nextRecords() {
$this->currentRow += $this->offsetRows ;
$this->showRecords() ;
}
// **************************************************
// PREVRECORDS
// Displays the previous nn offset records if not at first
// **************************************************
function prevRecords() {
$this->currentRow -= $this->offsetRows ;
if( $this->currentRows < 0 )
$this->currentRows = 0 ;
$this->showRecords() ;
}
}

Then my form works as follows:
------------------------------
<FORM action="<?=$_SERVER['PHP_SELF']?>" method="post">
<?php
require_once( "class_welcome.php" ) ;
if( !$welcome ) {
$welcome =& Welcome::getInstance() ;
}

if(isset($_POST['next'])) {
$welcome->nextRecords() ;
}
else {
if(isset($_POST['previous'])) {
$welcome->prevRecords() ;
}
else {
$welcome->showRecords() ;
}
}
?>

<P>
<INPUT name="previous" type="submit" value="<<" />
<INPUT name="next" type="submit" value=">>" />
</FORM>

View Replies !
Permission Denied Trying To Include() World-readable File
include('./include/constants.inc.php');

Warning: main(./include/constants.inc.php) [function.main]: failed to open stream: Permission denied in /var/www/html/tools/app/index.php on line 43

The file "constants.inc.php" has permissions of 0774, it's world readable. I am at a loss. Even increased all the way to 0777, to no avail, still get "Permission denied".

View Replies !
Green Bean Question On Singleton Php5
I am implementing this:

class dbaccess{
static $db=null;
static $othervar=33;
<p> private function dbaccess(){
dbaccess::$db= new mysqli("localhost",USER,PASSWD ,DB);
if(mysqli_connect_errno()){
echo "no way";
}
}
<p>public static function GetDb(){
if(dbaccess::$db==null){...

View Replies !
Singleton Pattern, Suitable For Multi-user Websites ?
I come from a Java background and I was just wondering if a Singleton
pattern is suitable for websites with heavy traffic.
Of course the most common example given is the DB connection, and maybe
a cache of connections, and a checkout/checkin strategy is more
appropriate.

Can use of a Singleton restrict resource usage and cause processing
backlogs, such as deadlock ?

View Replies !
Using The "static" Keyword To Implement The Singleton Pattern
To call I would do something like:

$headline = McSelectJustOneField::callDatastore("cbHeadline");

Is this the correct use of the static keyword, to implement a
Singleton design?

class McSelectJustOneField extends McSelect {

/**
* 11-21-03 - getter
* @param - $infoToBeSought, in this case, is the name of the field
whose contents are wanted.
* returns mixed (could be string or integer or whatever was in the
field)
function static callDatastore($infoToBeSought) {
$this->setQueryObject("GetJustOneField");
$this->setInfoToBeSought($infoToBeSought);
$this->getInfo();
$row = $this->getRowAsArrayWithStringIndex($this->dsResultPointer);
$field = $row[0];
return $field;
}

}

View Replies !
Defining A Class/instantiating Object Inside A Method Of Another Class
I have a class. Inside the class I have a method that reads a text file.
In the text file I have a class name and a file name where that class is
defined. Now, I need to instantiate an object of that class, the problem
being that at the time I find out the class name and the file name, I'm
inside a method of another class. Well, let me just type up a little
example:

View Replies !
Static Classes Vs. Singleton Classes Vs. Globals
Sometimes I want to use certain data and functions anywhere in my code;
for example, when writing logging routines. In PHP5 I could write a
class with all static members and functions, a singleton class, or a
regular class assigned to a global variable. What would be the
advantages of each?

In Java web-apps (or in non-web applications), these classes persist
for much longer, so it's easier to see the reasons for using them. But
in PHP, it seems like you could do pretty much the same thing with all
three.



View Replies !
Real Ip Behind A Proxy
is there any way to know the real ip, for people behind a proxy?

View Replies !
Getting The REAL Directory?
Is there any way to get the directory/path of the file running the script, not the directory you're inside (Via dir())? I'm allowing the user to navigate through directories, and that part works great - but whenever I attempt to used getcwd(), it returns the directory the user is in - not the directory of the php file - is there any way to get the directory of the .php file the user is using?

View Replies !
Real Estate MLS/IDX
I am trying to program an MLS/IDX search feature to be integrated into a real estate website. This progrom will allow MLS/IDX searching/browsing (searching by MLS #, house variables, etc) and browsing by property location, etc.

I have come accross RETS and have tried to go about it, but wow, maybe MLS/IDX is just some mythical database that doesn't exist? If anyone can help me out here. show some code, point me to a resource, tutorial, something that would be some assistance, I would bow down to them, and mail them one, yes, one ice cold root beer.

View Replies !
Resolve Real IP
I can get the apparent IP from $_SERVER['REMOTE_ADDR']; . However, how can I find the real IP if the user is behind a proxy? I know it must be possible as some "whatismyip" sites do it.

View Replies !
Mysql Real
I found this which I think calls for an indepth brain storming. A very good reading

[edited by: eelixduppy at 1:06 pm (utc) on Sep. 12, 2007]
[edit reason] fixed typo as per request [/edit]

View Replies !
Child Class Member's Iteration By Parent Class
I have a class that has a few private members. Is there a way to create a function in its parent class that can access its (child's) private members.

With the following code I am able to get only the public and protected members.

class parentIter {

function iterateProps ( ) {
foreach ( $this as $propName => $propValue ) {
echo "<br>$propName => $propValue" ;
}
}
}

class childIter extends parentIter {
protected $var1 = 'protected var' ;
private $var2 = 'private var' ;
public $var3 = 'public var' ;

function iterateProps ( ) {
parent::iterateProps () ;
}
}
$obj = new childIter () ;
$obj->iterateProps ( ) ;

View Replies !
PHP5: Can A Class Inherit Initialized Classvariable From Another Class?
I got following problem trying to inherit a variable from another class

class Core
{
public $obj;

function initialize($obj)
{
$this->obj = $obj;
}

}

class test extends Core
{
function test()
{
echo $this->obj;
// or
echo parent::$obj;
// ??
}

}

$core = new Core
$core->initialize('hello');

$test = new test
$test->test();

As far as what I would like to get, I would see 'hello', but instead I
get following error:
Fatal error: Access to undeclared static property: Core::$obj (echo
parent::$obj;)
After declaring $obj as public and static I don't get any result as
well..
Is it possible to inherit already initialized variables from a
different class or are there design patterns who could do something
like that? I hope it is clear where I want to go with this..
I am doing this because I can't give the class test any parameters
because it could be extended (class woow extends test). Also the amount
of variables is not certain and there might be lots of classes needing
to inherit the variables. That would mean that I would have to change
every class if a parameter would change..

View Replies !
Access Class Member Function Without Instantiating Class?
I need to access a class member function from outside the class, and hopefully without having to instantiate the class if possible?

I have an HTML form <select> and each <option> item is being pulled from an array stored in a mysql db.  But I'm doing this independently of the normal purpose of the class itself, I just want to use that member function.

View Replies !
Modify A Function Of A Parent Class From The Child Class ?
How do i modify a function of a parent class from the child class ?

View Replies !
Date :: Class Starts And The Time A Class Ends
I have a registeration system set up. The user registers the time a class starts and the time a class ends. These times are stored in mysql db with time type. How do I prevent double booking in this situation? e.g. If the class starts at 9:00 and ends at 10:30, how do I ensure that no class takes place between those times.

View Replies !
Real-time Output?
I'm a relative PHP newbie, so I apologize if this is a simple question.

Anyway, here's my problem. I'm using a PHP script to pre-render a bunchload of insert files for an HTML page. Right now there's about 1,600, but that number could get much, much higher when the site goes live.

I'll only need to re-render the whole batch once or twice a year (if that) but it's still something I'd like to be able to do in case I have to move the site to a different server, or there's a hard drive crash or etc.

Basically what the script does is grab a whole bunch of information from a database and write the insert file. It does this for every single one.

The problem of course, is that PHP by default does all this server-side, and then sends it to the browser. Because this process takes like ten or twenty minutes to do, the browser times out long before it's finished.

Is there a way to get progressive output with PHP? Or do I need to re-do this in another language like Perl?

View Replies !
Real Length Of Arrays
Sometimes, I want to know how many elements are really in an array (php3).

The count() and sizeof() functions apparently return the number of non-empty array elements, and if you do a while loop checking for empty will stop on the first empty element.

I have been using the following function:
function truecount($theArray) {
if (is_array($theArray)) {
end($theArray);
return key($theArray);
}
}
but if the key is non-numeric, won't that trip me up?
Anyone have a better solution?

View Replies !
Md5 / Sha1 - Any Real Difference?
I use md5 hash with some of my cookies and occassionally a hidden form
field - I know the physical data on my network is insecure (unless being
served via https) but I was wondering if there are any advantages to using
md5 over sha1 or versa vicea... I know md5 gives me a unique 32bit hash
while sha1 I've read is 'secure' (?) and gives a 40bit hash... Since The
technical webpage on sha1 is lengthy and for the most part over my head...
and other than today, I've never heard of it before... I was wondering if
anyone could offer any comments on it...

View Replies !
Real Time Chat
There's anyone out there that can give me a light on real time chat using sockets. I've seen some using push technics but they all hang up after an elapsed amount of time.

View Replies !
Htmlspecialchars/real Escape
I'm creating a BBCode parser, and everything's working but one thing; I need code tags, but I will need to real_escape/htmlspecialchars the post to make sure it isn't malicious. The only problem is if I real_escape with code tags that contain php, the php will be removed. If I specialchars the post with php, I can't have syntax highlighting (or, not easily). How do I get round this?

View Replies !
Real IP Address From Behind Proxy Or NAT
How to get the real IP address of a user, not that of their proxy server or the external NAT address. I was quite sure that this wasn't possible without some kind of process getting the address on the client machine.

I have suggested that these sites could be using Java to get the real IP address, however, I could be wrong and for me the script that I found always returns 127.0.0.1 . This suggests to me that any script attempting to obtain the hosts real IP address infarct rely s on the HTTP-X-FORWARDED-FOR header sent by the proxy server...

View Replies !
Real-time Clock
Where should I start to write a Real-time Clock? I want it be dynamic, not static. I know how to get the time and display it but how do I keep changing it ?

View Replies !
My Real Estate Scripts
I have been writing a real estate agency program and its coming on well but taking longer than I thought. Also I think I am just re-inventing the wheel as I guess like BB scripts there are probably good free ones already writen in php and using mysql ? Can anyone recommend one.? can then continue learning while adapting it to my purposes.

View Replies !
REAL E-mail Validation
if there is a way to actually send an e-mail to the server and see if it bounces or not? What I'm trying to do is require users to enter a valid e-mail address on the front page before entering the site. I don't want to do simple character validation (check for @ and no special chars, etc, etc) but actually see if the e-mail account truly exists before letting them into the site.

View Replies !
Real-time Chat
I wrote a PHP chat system similar to gChat which simply uses constant ajax calls to update the chat. This system is fine for a few users, but with potentially thousands of users, it is much too hard on the server. I've been considering taking the 'Comet' route, but have heard that PHP can't handle Comet very well. What would be the best language/API to perform real-time chat for a large user-base?

View Replies !
Date In Real Time
It is possible to create a program which get the date in real time using PHP.

View Replies !
Real Time Sql Query
I am making a web-based chat but to get the msg from the database i need to refresh the page and that will make load and extra bandwidth on the server so i want to make the query in real time ( only the new msg to be received without refresh the whole page ), Any one in here knows how to get data from sql database without having to refresh page.

View Replies !
Real Media Player Pop Up
Does anybody have any idea on how to make a pop up player for playing streaming real media files like Code:

View Replies !
Mysql Real Escape
Upon entry into the database, I first clean form input data with html special characters, strip tags, and mysql real escape string. When I retrieve this data from the db, single quotes aren't coming out right on the pages. Some browsers display a question mark, others a blank space, and another (FireFox) totally screws up the text formatting.

View Replies !
Real Escape String
How can i add a escape string to this php mysql query.

mysql_query('insert into times (code, date, time, duration) values ("'.$course_code.'","'.$date_inSQL.'","'.$time_inSQL.'","'.$duration.'" )');

View Replies !
Calling Class Method Of Variable Class.
Yes, it's the week of OO here in c.l.php

If I want to call the method a class (not an object), one normally uses:
classname::method();

which works fine.

However, what if I don't know the classname yet?
$classname::method();
doesn't work, neither does
{$classname}::method();

I've got solved it like this now:
call_user_func(array($classname,'method'));

View Replies !

Copyright © 2005-08 www.BigResource.com, All rights reserved