Précédent   Forum des professionnels en informatique > PHP > Langage > Syntaxe
Syntaxe Forum d'entraide sur la syntaxe de PHP et la POO. Avant de poster -> FAQ syntaxe, Cours d'initiation et cours de POO
Partagez cette discussion sur d'autres réseaux sociaux : Viadeo Twitter Google Facebook Digg Delicious MySpace Yahoo
Réponse Proposer ce sujet en actualité
 
Outils de la discussion
Publicité
'
Vieux 21/01/2011, 18h24   #1
Débutant
 
Avatar de ETVigan
 
Homme Esteban
Conseil - Consultant en systèmes d'information
Inscription : avril 2010
Messages : 632
Détails du profil
Informations personnelles :
Nom : Homme Esteban
Localisation : France, Gard (Languedoc Roussillon)

Informations professionnelles :
Activité : Conseil - Consultant en systèmes d'information
Secteur : Finance

Informations forums :
Inscription : avril 2010
Messages : 632
Points : 122
Points : 122
Envoyer un message via MSN à ETVigan Envoyer un message via Skype™ à ETVigan
Par défaut Singleton et allocation autres classes

Bonjour,
Je suis entrain de développer un skelet de transaction basé sur le modèle Singleton.
Jusque là, pas de problème.
Mais si j'instancie une autre classe, là j'ai un soucis.

Voici mon skeleton

Code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
<?php
define ("SKELT_INIT" , "SKELT_INIT") ; 
define ("SKELT_BODY" , "SKELT_BODY") ; 
define ("SKELT_END"  , "SKELT_END" ) ;

require_once $_SERVER['DOCUMENT_ROOT'] . '/class/classlang.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/class/errorlogging.php';

/*
* A true Skeleton in PHP
* @author E.Mathot
* @version 1.0.0
* @name Skeleton.php
*/

class Skeleton 
{	static  $obj = array();
	static  $iteration 		  ;
	static  $TheInstance  ;
	static  $array_iteration = array(SKELT_INIT => 0, SKELT_BODY => 5, SKELT_END => 9) ;
		
/**
* Empêche la copie externe de l'instance.
*/
    private function __clone () 
	{}
 
/**
* Empêche la création externe d'instances.
*/
	private function __construct() 							// The constructor of the class is decleared as private 
	{ 							 							// so no it is not possible to create an instance of the 
	}							 							// Skeleton outside the class.
	
		
/**
* Renvoi de l'instance et initialisation si nécessaire.
*/
	public static function instantiate() 					// Static function that creats the instance of the class.
	{	if (Skeleton::$TheInstance == NULL) 				// Create a new object of Skeleton when there is
			Skeleton::$TheInstance = new Skeleton();		// no previous instace present.
		$instanceReferance =& Skeleton::$TheInstance;		// If there is already an instance exists then return  
															// the referance of the old  Instance.
		
		Skeleton::setIteration(SKELT_INIT) ;
		return($instanceReferance) ;						// the referance of the old  Instance.
	}
		
/**
* Process of Skeleton.
*/
	public static function process() 						// Static function to process() Skeleton.
	{	foreach(Skeleton::$array_iteration as $key => $data)
		{	//
			var_dump($key,$data) ;
		}
	}
/**
* Init process of Skeleton.
*/
	public static function initiate() 						// Static function to initiate() process.
	{	if (Skeleton::$iteration != SKELT_INIT)
	 		user_error("Bad Iteration[".Skeleton::$iteration."]" , E_USER_ERROR) ;
//
		$errorlog = new ErrorLogging();
//
		$param = array() ;
		call_user_func('trx_initiate', $param); 

//
//		$this->nextIteration() ;
	}
	
		
/**
* Execute process of Skeleton.
*/
	public static function execute() 						// Static function to execute() process.
	{	print("Execute()" ) ;
	}
		
/**
* Ending process of Skeleton.
*/
	private static function ending() 						// Static function to ending() process.
	{	print("Ending()" ) ;
	}
	
/**
* SetIteration of Skeleton.
*/
	public static function setIteration($iter) 				// Static function SET Iteration phase of skeleton.
	{	if (in_array($iter,Skeleton::$array_iteration) )
			Skeleton::$iteration = $iter ;
		else
			user_error("BAd Iteration[".$Iter."]", E_USER_ERROR) ;
	}
	
/**
* GetIteration of Skeleton.
*/
	public static function getIteration() 					// Static function GET Iteration phase of skeleton.
	{	return(Skeleton::$iteration) ; 	}
	
/**
* NextIteration of Skeleton.
*/
	public static function nextIteration() 					// Static function GET Iteration phase of skeleton.
	{	return($this->iteratioàn) ; 	}
/* ============================================================================================================================================== */	
	public function get($key)			
	{
		 return $this->obj[$key];
	}
		
	public function put($key,$object)
	{
		if ($this->obj[$key]==NULL)		
		  	$this->obj[$key]=$object;
	}
		
	public function kill($key)
	{
		unset($this->obj[$key]);
		return (isset($this->obj[$key]));
	}
/**
* End of Class Skeleton.
*/
} 	
?>
Quand j'essaye de faire:
Code :
1
2
 
		$errorlog = new ErrorLogging();
en ligne 65 du skelet, j'attrape dans le log PHP:
Code :
[21-Jan-2011 18:10:20] PHP Fatal error:  Call to private ErrorLogging::__construct() from context 'Skeleton' in F:\WebSites\esteban\class\skeleton.php on line 65
Cette classe ErrorLogging n'est pas du modèle Singleton.
Code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
 
<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/errorlogging.php';
 
class ErrorLogging
{
	/**
	 * @var $_backTrace Backtrace message in _customError() method
	 * @see _customError
	 */
	private $_backTrace;
 
	/**
	 * @var $_errorMessage Error message
	 * @see _customError
	 */
	private $_errorMessage;
 
	/**
	 * @var $_traceMessage Contains the backtrace message from _debugBacktrace() method
	 * @see _debugBacktrace()
	 */
	private $_traceMessage = '';
 
	/**
	 * @var $MAXLENGTH Maximum length for backtrace message
	 * @see _debugBacktrace()
	 */
	private $_MAXLENGTH = 64;
 
	/**
	 * @var $_traceArray Contains from debug_backtrace()
	 * @see _debugBacktrace()
	 */
	private $_traceArray;
 
	/**
	 * @var $_defineTabs
	 */
	private $_defineTabs;
 
	/**
	 * @var $_argsDefine
	 */
	private $_argsDefine = array();
 
	/**
	 * @var $_newArray
	 */
	private $_newArray;
 
	/**
	 * @var $_newValue
	 */
	private $_newValue;
 
	/**
	 * @var $_stringValue
	 */
	private $_stringValue;
 
	/**
	 * @var $_lineNumber
	 */
	private $_lineNumber;
 
	/**
	 * @var $_fileName
	 */
	private $_fileName;
 
	/**
	 * @var $_lastError
	 */
	private $_lastError;
 
 
	/**
	 * Set custom error handler
	 * 
	 * @param none
	 * @return none
	 */
	private function __construct()
	{
		error_reporting(1);
		set_error_handler(array($this,'_customError'), E_ALL ^ E_NOTICE);
		register_shutdown_function(array($this, '_fatalError'));
	}
 
	/**
	 * Custom error logging in custom format
	 * 
	 * @param Int $errNo Error number
	 * @param String $errStr Error string
	 * @param String $errFile Error file
	 * @param Int $errLine Error line
	 * @return none
	 */
	private function _customError($errNo, $errStr, $errFile, $errLine)
	{
		if(error_reporting()==0)
		{
			return;
		}
		$this->_backTrace = $this->_debugBacktrace(2);
 
		$this->_errorMessage = "\n<h1>Website Generic Error</h1>";
		$this->_errorMessage .= "\n<b>ERROR NO : </b><font color='red'>{$errNo}</font>";
		$this->_errorMessage .= "\n<b>TEXT : </b><font color='red'>{$errStr}</font>";
		$this->_errorMessage .= "\n<b>LOCATION : </b><font color='red'>{$errFile}</font>, <b>line</b> {$errLine}, at ".date("F j, Y, g:i a");
		$this->_errorMessage .= "\n<b>Showing Backtrace : </b>\n{$this->_backTrace} \n\n";
 
		if(SEND_ERROR_MAIL == TRUE)
		{
			error_log($this->_errorMessage, 1, ADMIN_ERROR_MAIL, "From: ".SEND_ERROR_FROM."\r\nTo: ".ADMIN_ERROR_MAIL);
		}
 
		if(ERROR_LOGGING==TRUE)
		{
			error_log($this->_errorMessage, 3, ERROR_LOGGING_FILE);
		}
 
		if(DEBUGGING == TRUE)
		{
				echo "<pre>".$this->_errorMessage."</pre>";
		}
		else
		{
			echo SITE_GENERIC_ERROR_MSG;
		}
		exit;
	}
 
	/**
	 * Build backtrace message
	 * 
	 * @param $_entriesMade Irrelevant entries in debug_backtrace, first two characters 
	 * @return  
	 */
	private function _debugBacktrace($_entriesMade)
	{
		$this->_traceArray = debug_backtrace();
 
		for($i=0;$i<$_entriesMade;$i++)
		{
			array_shift($this->_traceArray);
		}
 
		$this->_defineTabs = sizeof($this->_traceArray)-1;
		foreach($this->_traceArray as $this->_newArray)
		{
			$this->_defineTabs -=1;
			if(isset($this->_newArray['class']))
			{
				$this->_traceMessage .= $this->_newArray['class'].'.';
			}
			if(!empty($this->_newArray['args']))
			{
				foreach($this->_newArray['args'] as $this->_newValue)
				{
					if(is_null($this->_newValue))
					{
						$this->_argsDefine[] = NULL; 
					}
					elseif(is_array($this->_newValue))
					{
						$this->_argsDefine[] = 'Array['.sizeof($this->_newValue).']';
					}
					elseif(is_object($this->_newValue))
					{
						$this->_argsDefine[] = 'Object: '.get_class($this->_newValue);
					}
					elseif(is_bool($this->_newValue))
					{
						$this->_argsDefine[] = $this->_newValue ? 'TRUE' : 'FALSE';
					}
					else
					{
						$this->_newValue = (string)@$this->_newValue;
						$this->_stringValue = htmlspecialchars(substr($this->_newValue, 0, $this->_MAXLENGTH));
						if(strlen($this->_newValue)>$this->_MAXLENGTH)
						{
							$this->_stringValue = '...';
						}
						$this->_argsDefine[] = "\"".$this->_stringValue."\""; 
					}
				}
			}
			$this->_traceMessage .= $this->_newArray['function'].'('.implode(',', $this->_argsDefine).')';
			$this->_lineNumber = (isset($this->_newArray['line']) ? $this->_newArray['line']:"unknown");
			$this->_fileName = (isset($this->_newArray['file']) ? $this->_newArray['file']:"unknown");
 
			$this->_traceMessage .= sprintf(" # line %4d. file: %s", $this->_lineNumber, $this->_fileName, $this->_fileName);
			$this->_traceMessage .= "\n";	
		}
		return $this->_traceMessage;
	}
 
	private function _fatalError()
	{
		$this->_lastError = error_get_last();
		if($this->_lastError['type'] == 1 || $this->_lastError['type'] == 4 || $this->_lastError['type'] == 16 || $this->_lastError['type'] == 64 || $this->_lastError['type'] == 256 || $this->_lastError['type'] == 4096)
		{
			$this->_customError($this->_lastError['type'], $this->_lastError['message'], $this->_lastError['file'], $this->_lastError['line']);
		}
	} 
 
}
?>
Le fichier inclut en ligne 2 de cette classe est:
Code :
1
2
3
4
5
6
7
8
9
10
11
12
 
/**
 * Error Handling Values
 */
define('DEBUGGING', TRUE);  
define('ADMIN_ERROR_MAIL', 'admin@admin.com');
define('SEND_ERROR_MAIL', FALSE);   
define('SEND_ERROR_FROM', 'errors@admin.com');
define('IS_WARNING_FATAL', TRUE);
define('ERROR_LOGGING', TRUE);
define('ERROR_LOGGING_FILE', 'path/to/log/file');
define('SITE_GENERIC_ERROR_MSG', '<h1>Portal Error!</h1>');
A l'écran, j'ai l'impression que la classe Errorlogfging a quand même fonctionné car j'ai:
Code :
1
2
3
4
 
/** * Error Handling Values */ define('DEBUGGING', TRUE); define('ADMIN_ERROR_MAIL', 'admin@admin.com'); define('SEND_ERROR_MAIL', FALSE); define('SEND_ERROR_FROM', 'errors@admin.com'); define('IS_WARNING_FATAL', TRUE); define('ERROR_LOGGING', TRUE); define('ERROR_LOGGING_FILE', 'path/to/log/file'); define('SITE_GENERIC_ERROR_MSG', '
Portal Error!
');
]Comment dois je écrire l'instanciation d'une classe à partir d'un modèle Singleton ?

J'ai déjà trouvé une chose:
Le constructor de error_logging est private, je l'ai mis public, cela va un poil mieux, j'ai le print(initiate) mais la même chose à l'écran !

J'ai trouvé autre chose que je ne comprends pas. Si je fais le paste du contenu du fichier /includes/errorlogging directement dans la classe, cela passe. Mais ne comprends pas la raison, pourquoi cela passe
Bonne question et merci à ceusss qui m'aideront
__________________
Esteban
ETVigan est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 22/01/2011, 00h17   #2
Modérateur
 
Avatar de Benjamin Delespierre
 
Benjamin Delespierre
Développeur Web
Inscription : février 2010
Messages : 2 984
Détails du profil
Informations personnelles :
Nom : Benjamin Delespierre
Âge : 24
Localisation : France

Informations professionnelles :
Activité : Développeur Web
Secteur : High Tech - Opérateur de télécommunications

Informations forums :
Inscription : février 2010
Messages : 2 984
Points : 5 015
Points : 5 015
Hello

Citation:
Le constructor de error_logging est private
S'il était en private c'est pour éviter qu'on ne fasse un new dessus. Tu devrais avoir une méthode statique instance ou instanciate quelque part dans ta classe, utilise là.

Tu connais le Singleton ou tu utilise un bout de code importé ?
__________________
A la recherche d'un framework MVC facile a prendre en main ? Essayez Axiom
Nouveau: la référence d'Axiom est disponible sur GitHub (je la peaufine en ce moment même).

Un problème correctement identifié est à moitié résolu, évitez de poster l'intégralité de votre code avec pour seule explication "ça ne marche pas...".
Pour identifier correctement vos problèmes PHP, utilisez la gestion des erreurs et xdebug.

Les boutons et existent, servez-vous en
Benjamin Delespierre est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 22/01/2011, 09h56   #3
Débutant
 
Avatar de ETVigan
 
Homme Esteban
Conseil - Consultant en systèmes d'information
Inscription : avril 2010
Messages : 632
Détails du profil
Informations personnelles :
Nom : Homme Esteban
Localisation : France, Gard (Languedoc Roussillon)

Informations professionnelles :
Activité : Conseil - Consultant en systèmes d'information
Secteur : Finance

Informations forums :
Inscription : avril 2010
Messages : 632
Points : 122
Points : 122
Envoyer un message via MSN à ETVigan Envoyer un message via Skype™ à ETVigan
Par défaut Singleton et allocation autres classes

Exact, et si tu es observateur, tu verrais que j'ai déjà (hier) màj le post en question en indiquant cette solution.
Mais cela ne change rien à mon problème....

Meri quand même

Donc, tjs open......
__________________
Esteban
ETVigan est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 22/01/2011, 10h04   #4
Débutant
 
Avatar de ETVigan
 
Homme Esteban
Conseil - Consultant en systèmes d'information
Inscription : avril 2010
Messages : 632
Détails du profil
Informations personnelles :
Nom : Homme Esteban
Localisation : France, Gard (Languedoc Roussillon)

Informations professionnelles :
Activité : Conseil - Consultant en systèmes d'information
Secteur : Finance

Informations forums :
Inscription : avril 2010
Messages : 632
Points : 122
Points : 122
Envoyer un message via MSN à ETVigan Envoyer un message via Skype™ à ETVigan
Par défaut Singleton et allocation autres classes

De mon fichier conf.inc original:

Code :
1
2
3
4
5
6
7
8
9
10
11
12
13
 
/**
 * Error Handling Values
 */
define("DEBUGGING", TRUE);  
define("ADMIN_ERROR_MAIL", "admin@admin.com");
define("SEND_ERROR_MAIL", FALSE);   
define("SEND_ERROR_FROM", "errors@admin.com");
define("IS_WARNING_FATAL", TRUE);
define("ERROR_LOGGING", TRUE);
define("ERROR_LOGGING_FILE", "path/to/log/file");
define("SITE_GENERIC_ERROR_MSG", "<h1>Portal Error!</h1>");
*/
J'ai cru qu'en le modifiant en:

Code :
1
2
3
4
5
6
7
8
9
 
define("DEBUGGING", TRUE);  
define("ADMIN_ERROR_MAIL", "admin@admin.com");
define("SEND_ERROR_MAIL", FALSE);   
define("SEND_ERROR_FROM", "errors@admin.com");
define("IS_WARNING_FATAL", TRUE);
define("ERROR_LOGGING", TRUE);
define("ERROR_LOGGING_FILE", "path/to/log/file");
define("SITE_GENERIC_ERROR_MSG", "<h1>Portal Error!</h1>");
CELA NE FONCTIONNE PAS ..... je me suis trompé entre mon petit test SANS Singleton et Skeleton....

Mais si le parser passe, je n'intercepte pas encore l'erreur alors que dans un petit test j'ai:

Code :
1
2
3
4
5
6
7
 
Website Generic Error
 
ERROR NO : 2
TEXT : Division by zero
LOCATION : F:\WebSites\errorlog\index.php, line 6, at January 22, 2011, 10:03 am
Showing Backtrace :
Dans mon Skeleton, j'ai bien l'appel à mon entry point (dans index.php) qui me dit:
Code :
1
2
3
4
5
6
7
8
 
function trx_initiate(array $param)
{	print("Start - initiate()") ; 
$i = 10 ;
$i = $i / 0 ;
	print("End - initiate()") ; 
	Skeleton::nextIteration() ;
}
Les 2 print() sont à l'ecran et m'erreur n'est pas interceptée !
Et rien dans le log PHP..... Je n'avance pas !
__________________
Esteban
ETVigan est déconnecté   Envoyer un message privé Réponse avec citation 00
Réponse Proposer ce sujet en actualité
Outils de la discussion



Fuseau horaire GMT +2. Il est actuellement 02h27.


 
 
 
 
Partenaires

Hébergement Web