Tag Archives: singleton

Web

Application configuration in AngularJS

angcfg
If you are developing angular web-application, you ask how to involve configuration in it. I propose next pattern: create constant service and inject it in your other modules, services etc.
About constant in AngularJS.

1. Create app module as app.js file:

var app = angular.module('app', []);

2. Define constant service as config.js file:

app.constant('config', {
    apiUrl: 'http://localhost/api/v1',
});

3. Get your service with injected config as services.js file:

app.factory('userService', ['$http', 'config',
    function ($http, config) {
        return {
            register: function (email, password) {
                return $http({
                    url: config.apiUrl + '/user',
                    method: 'POST',
                    data: {
                        'Email': email,
                        'Password': password
                    }
                });
            },
            login: function (email, password) {
                return $http({
                    url: config.apiUrl + '/auth',
                    method: 'POST',
                    data: {
                        'Email': email,
                        'Password': password
                    }
                });
            },
            logout: function () {
                return $http({
                    url: config.apiUrl + '/auth',
                    method: 'DELETE'
                });
            },
            checkAuth: function () {
                return $http({
                    url: config.apiUrl + '/auth',
                    method: 'GET'
                });
            }
        };
}]);

So, config service is a singleton can be injected in any other services, modules etc.

PHP

Singleton design pattern in PHP


When you need a single instance of some class, use pattern:

class MySingleton
{
	static private $instance = null;

	static public function createInstance($args = null)
	{
		if (self::$instance == null)
			self::$instance = new self($args);

		return self::$instance;
	}
	static public function destroyInstance()
	{
		return (self::$instance = null);
	}

	protected function __construct($args = null)
	{
		// your code...
	}
	protected function __clone()
	{
	}
}

Also, can be useful What is new in PHP 5.3 – part 2: late static binding