Page 1 of 1

static classes or singletons

Posted: Tue Apr 05, 2005 4:29 pm
by andre_c
I have a few classes in the Services layer that i want to implement:
This is 2 of them:

Code: Select all

<?
class UserManager {
  public function getUserById( $id ) {
    ...
  }

  public function getAdsByUserId( $id ) {
    ...
  }

  // etc
}

class PublicationManager {
  public function getPublicationById( $id ) {
    ...
  }
  
  public function getPublicationsByClientId( $client_id ) {
    ...
  }
  
  // etc
}

?>
do you recommend using a static class, singletons for each class, or simply creating a new instance as needed (since there's no properties to store)?

Posted: Tue Apr 05, 2005 4:59 pm
by SystemWisdom
Right away im thinking Singletons, since it seems you are only using the class for organizational/scope purposes.. Instantiating an object would be pointless, and you would have to add a global statement to any other function that wants to access its methods..

Personally, I would just use scope resolution:

Code: Select all

UserManager::getUserById( 1000 );
I like it better because it is clear which class the function belongs too..

That's just my opinion..

Posted: Tue Apr 05, 2005 5:28 pm
by McGruff
Small point: these look like Finders?

Instantiate an object. You might need to configure it at instantiation. With statically called methods, the Finder has no state (it doesn't exist as an object, of course).

Code: Select all

$user_finder =& new UserFinderFromDatabase($db);

// or:
$user_finder =& new UserFinderFromFile('path/to/users_file');

// in either case:
$user =& $user_finder->findById($id);
Avoid singletons if you can. Avoid globals at all costs. Globals are evil. Singletons slightly less so. Here's an article on Registry.

Posted: Tue Apr 05, 2005 6:27 pm
by andre_c
i'm leaning towards instantiating them every time, since i don't like singletons either and i guess they might end up having configuration properties (like McGruff says).

Are the ampersands still necessary in PHP5?

Posted: Tue Apr 05, 2005 7:22 pm
by McGruff
Ampersands: no not in php5.

Posted: Tue Apr 05, 2005 8:35 pm
by andre_c
Ok Thanks,
I ended up implementing the classes the way that McGruff said.
It's an extra step but it seems to be the best since i can configure the objects if they need to be configured and instantiation doesn't really cost me much.

Static classes seem kind of similar to using global objects... i don't know, i get that same feeling with singletons too...