Asked  2 Years ago    Answers:  5   Viewed   132 times

Possible Duplicate:
Who needs singletons?

I always write with respect to best practice, but I also want to understand why a given thing is a best practice.

I've read on in an article (I unfortunately don't remember) that singleton classes are prefered to be instantiated, rather than being made with static functions and accessed with the scope resolution operator (::). So if I have a class that contains all my tools to validate, in short:

class validate {
    private function __construct(){}
    public static function email($input){
        return true;

I've been told this is considered bad practice (or at least warned against), because of such things as the garbage collector and maintenance. So what the critiques of the "singleton class as static methods" wants, is that I instantiate a class I'm 100% certain I will only ever instantiate once. To me it seems like doing "double work", because it's all ready there. What am I missing?

What's the view on the matter? Of course it's not a life and death issue, but one might as well do a thing the right way, if the option is there :)



An example singleton classes in php:
Creating the Singleton design pattern in PHP5 : Ans 1 :
Creating the Singleton design pattern in PHP5 : Ans 2 :

Singleton is considered "bad practice".

Mainly because of this: How is testing the registry pattern or singleton hard in PHP?

  • why are singleton bad?

  • why singletons are evil?

  • A good approach: Dependency Injection

  • Presentation on reusability: Decouple your PHP code for reusability

  • Do you need a dependency injection container

  • Static methods vs singletons choose neither

  • The Clean Code Talks - "Global State and Singletons"

  • Inversion of Control Containers and the Dependency Injection pattern

Wanna

  • What are the disadvantages of using a PHP database class as a singleton?

  • Database abstraction class design using PHP PDO

  • Would singleton be a good design pattern for a microblogging site?

  • Modifying a class to encapsulate instead of inherit

  • How to access an object from another class?

  • Testing Code That Uses Singletons

A Singleton decision diagram (source):

Saturday, October 8, 2022

Searching the actual database is fine until you want to add snazzy features like the one above. In my experience it is best to create a dedicated search table, with keywords and page IDs/URLs/etc. Then populate this table every n hours with content. During this population you can add snippets for each document for each keyword.

Alternatively a quick hack might be:

$text = 'This is an example text page with content. It could be red, green or blue.';
$keyword = 'red';
$size = 5; // size of snippet either side of keyword

$snippet = '...'.substr($text, strpos($text, $keyword) - $size, strpos($text, $keyword) + sizeof($keyword) + $size).'...';
$snippet = str_replace($keyword, '<strong>'.$keyword.'</strong>', $snippet);
echo $snippet;
Wednesday, September 14, 2022

Inheriting Singleton class in PHP is difficult, event in PHP 7.0, but you can do this with some changes on your class to work.

first make your Singleton class to abstract

abstract class Singleton {


change your $instance variable to array $instance(s)

private $instances = [];

Now change getInstance() method like below

public static function getInstance() {
  if (!isset(self::$instances[static::class]) {
    self::$instances[static::class] = new static();

  return self::$instances[static::class];

And change your test

remember now you can't call Singleton:: getInstance() due to abstract

class SingletonChild extends Singleton {

class SingletonChildTwo extends SingletonChild {

$obj = SingletonChild::getInstance();
$obj_two = SingletonChildTwo::getInstance();
var_dump($obj === SingletonChild::getInstance()); // true
var_dump($obj === $obj_two); // will -> false
Wednesday, August 10, 2022

I'd go with autoloading. You don't have to worry about where you require_once() your classes if it does it automatically for you. All you have to do is start using the classes you expect to be there, and PHP will call your autoloader to make sure that the classes are loaded.

If you are more used to programming in an environment that has you import things at the top of each file, you might be more comfortable using require_once() at the top of all of your files. I almost prefer this over autoloading because it makes it very clear what each classes dependencies are. However, you get a lot of duplication which you might not enjoy.

Either way works. It is mostly a style choice.

Sunday, December 18, 2022

Inner classes (static or not) have exactly the same access to their enclosing class' fields and methods as anonymous classes, the difference between static inner classes (actually called nested classes) and (regular, non-static) inner classes being that the static one need an explicit reference to an instance of the enclosing class to access something. Of course, when you need to do that, it's usually on the instance of the enclosing class that created the inner class, so it's easier and clearer to use a non-static inner class.


  • Inner class (non-static)

    class A {
        private int field;
        private class B {
            public void doSomething() {
                field++; // Valid
  • Nested class (i.e. "static inner class")

    class A {
        private int field;
        private static class B {
            public void doSomething(A a) {
                a.field++; // Valid
  • Anonymous class

    class A {
        private int field;
        public void doSomething() {
            new Runnable() {
                public void run() {
                    field++; // Valid

Whether you use that accessibility is another question. If you do access private fields of the enclosing class, there'll be an accessor generated, so it could impact the performance as the cost of calling a method is not the same as accessing a field, but it will probably be negligible in most cases. You should always write correct code first (both in terms of design and functionality) before doing micro-optimizations not based on any measurement. The JIT compiler does a lot of things for you anyway.

Wednesday, August 24, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :

Browse Other Code Languages