Development

/branches/1.4/lib/util/sfContext.class.php

You must first sign up to be able to contribute.

root/branches/1.4/lib/util/sfContext.class.php

Revision 23922, 15.7 kB (checked in by fabien, 4 years ago)

[1.4] removed deprecated stuff

  • Property svn:mime-type set to text/x-php
  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
Line 
1 <?php
2
3 /*
4  * This file is part of the symfony package.
5  * (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
6  * (c) 2004-2006 Sean Kerr <sean@code-box.org>
7  *
8  * For the full copyright and license information, please view the LICENSE
9  * file that was distributed with this source code.
10  */
11
12 /**
13  * sfContext provides information about the current application context, such as
14  * the module and action names and the module directory. References to the
15  * main symfony instances are also provided.
16  *
17  * @package    symfony
18  * @subpackage util
19  * @author     Fabien Potencier <fabien.potencier@symfony-project.com>
20  * @author     Sean Kerr <sean@code-box.org>
21  * @version    SVN: $Id$
22  */
23 class sfContext implements ArrayAccess
24 {
25   protected
26     $dispatcher          = null,
27     $configuration       = null,
28     $mailerConfiguration = array(),
29     $factories           = array();
30
31   protected static
32     $instances = array(),
33     $current   = 'default';
34
35   /**
36    * Creates a new context instance.
37    *
38    * @param  sfApplicationConfiguration $configuration  An sfApplicationConfiguration instance
39    * @param  string                     $name           A name for this context (application name by default)
40    * @param  string                     $class          The context class to use (sfContext by default)
41    *
42    * @return sfContext                  An sfContext instance
43    */
44   static public function createInstance(sfApplicationConfiguration $configuration, $name = null, $class = __CLASS__)
45   {
46     if (null === $name)
47     {
48       $name = $configuration->getApplication();
49     }
50
51     self::$current = $name;
52
53     self::$instances[$name] = new $class();
54
55     if (!self::$instances[$name] instanceof sfContext)
56     {
57       throw new sfFactoryException(sprintf('Class "%s" is not of the type sfContext.', $class));
58     }
59
60     self::$instances[$name]->initialize($configuration);
61
62     return self::$instances[$name];
63   }
64
65   /**
66    * Initializes the current sfContext instance.
67    *
68    * @param sfApplicationConfiguration $configuration  An sfApplicationConfiguration instance
69    */
70   public function initialize(sfApplicationConfiguration $configuration)
71   {
72     $this->configuration = $configuration;
73     $this->dispatcher    = $configuration->getEventDispatcher();
74
75     try
76     {
77       $this->loadFactories();
78     }
79     catch (sfException $e)
80     {
81       $e->printStackTrace();
82     }
83     catch (Exception $e)
84     {
85       sfException::createFromException($e)->printStackTrace();
86     }
87
88     $this->dispatcher->connect('template.filter_parameters', array($this, 'filterTemplateParameters'));
89
90     // register our shutdown function
91     register_shutdown_function(array($this, 'shutdown'));
92   }
93
94   /**
95    * Retrieves the singleton instance of this class.
96    *
97    * @param  string    $name   The name of the sfContext to retrieve.
98    * @param  string    $class  The context class to use (sfContext by default)
99    *
100    * @return sfContext An sfContext implementation instance.
101    */
102   static public function getInstance($name = null, $class = __CLASS__)
103   {
104     if (null === $name)
105     {
106       $name = self::$current;
107     }
108
109     if (!isset(self::$instances[$name]))
110     {
111       throw new sfException(sprintf('The "%s" context does not exist.', $name));
112     }
113
114     return self::$instances[$name];
115   }
116
117   /**
118    * Checks to see if there has been a context created
119    *
120    * @param  string $name  The name of the sfContext to check for
121    *
122    * @return bool true is instanced, otherwise false
123    */
124
125   public static function hasInstance($name = null)
126   {
127     if (null === $name)
128     {
129       $name = self::$current;
130     }
131
132     return isset(self::$instances[$name]);
133   }
134
135   /**
136    * Loads the symfony factories.
137    */
138   public function loadFactories()
139   {
140     if (sfConfig::get('sf_use_database'))
141     {
142       // setup our database connections
143       $this->factories['databaseManager'] = new sfDatabaseManager($this->configuration, array('auto_shutdown' => false));
144     }
145
146     // create a new action stack
147     $this->factories['actionStack'] = new sfActionStack();
148
149     if (sfConfig::get('sf_debug') && sfConfig::get('sf_logging_enabled'))
150     {
151       $timer = sfTimerManager::getTimer('Factories');
152     }
153
154     // include the factories configuration
155     require($this->configuration->getConfigCache()->checkConfig('config/factories.yml'));
156
157     $this->dispatcher->notify(new sfEvent($this, 'context.load_factories'));
158
159     if (sfConfig::get('sf_debug') && sfConfig::get('sf_logging_enabled'))
160     {
161       $timer->addTime();
162     }
163   }
164
165   /**
166    * Dispatches the current request.
167    */
168   public function dispatch()
169   {
170     $this->getController()->dispatch();
171   }
172
173   /**
174    * Sets the current context to something else
175    *
176    * @param string $name  The name of the context to switch to
177    *
178    */
179   public static function switchTo($name)
180   {
181     if (!isset(self::$instances[$name]))
182     {
183       $currentConfiguration = sfContext::getInstance()->getConfiguration();
184       sfContext::createInstance(ProjectConfiguration::getApplicationConfiguration($name, $currentConfiguration->getEnvironment(), $currentConfiguration->isDebug()));
185     }
186
187     self::$current = $name;
188
189     sfContext::getInstance()->getConfiguration()->activate();
190   }
191
192   /**
193    * Returns the configuration instance.
194    *
195    * @return sfApplicationConfiguration  The current application configuration instance
196    */
197   public function getConfiguration()
198   {
199     return $this->configuration;
200   }
201
202   /**
203    * Retrieves the current event dispatcher.
204    *
205    * @return sfEventDispatcher An sfEventDispatcher instance
206    */
207   public function getEventDispatcher()
208   {
209     return $this->dispatcher;
210   }
211
212   /**
213    * Retrieve the action name for this context.
214    *
215    * @return string The currently executing action name, if one is set,
216    *                otherwise null.
217    */
218   public function getActionName()
219   {
220     // get the last action stack entry
221     if ($this->factories['actionStack'] && $lastEntry = $this->factories['actionStack']->getLastEntry())
222     {
223       return $lastEntry->getActionName();
224     }
225   }
226
227
228   /**
229    * Retrieve the ActionStack.
230    *
231    * @return sfActionStack the sfActionStack instance
232    */
233   public function getActionStack()
234   {
235     return $this->factories['actionStack'];
236   }
237
238   /**
239    * Retrieve the controller.
240    *
241    * @return sfController The current sfController implementation instance.
242    */
243    public function getController()
244    {
245      return isset($this->factories['controller']) ? $this->factories['controller'] : null;
246    }
247
248    /**
249     * Retrieves the mailer.
250     *
251     * @return sfMailer The current sfMailer implementation instance.
252     */
253    public function getMailer()
254    {
255      if (!isset($this->factories['mailer']))
256      {
257        $this->factories['mailer'] = new $this->mailerConfiguration['class']($this->dispatcher, $this->mailerConfiguration);
258      }
259
260      return $this->factories['mailer'];
261    }
262
263    public function setMailerConfiguration($configuration)
264    {
265      $this->mailerConfiguration = $configuration;
266    }
267
268    /**
269     * Retrieve the logger.
270     *
271     * @return sfLogger The current sfLogger implementation instance.
272     */
273    public function getLogger()
274    {
275      if (!isset($this->factories['logger']))
276      {
277        $this->factories['logger'] = new sfNoLogger($this->dispatcher);
278      }
279
280      return $this->factories['logger'];
281    }
282
283   /**
284    * Retrieve a database connection from the database manager.
285    *
286    * This is a shortcut to manually getting a connection from an existing
287    * database implementation instance.
288    *
289    * If the [sf_use_database] setting is off, this will return null.
290    *
291    * @param  name  $name  A database name.
292    *
293    * @return mixed A database instance.
294    *
295    * @throws sfDatabaseException if the requested database name does not exist.
296    */
297   public function getDatabaseConnection($name = 'default')
298   {
299     if (null !== $this->factories['databaseManager'])
300     {
301       return $this->factories['databaseManager']->getDatabase($name)->getConnection();
302     }
303
304     return null;
305   }
306
307   /**
308    * Retrieve the database manager.
309    *
310    * @return sfDatabaseManager The current sfDatabaseManager instance.
311    */
312   public function getDatabaseManager()
313   {
314     return isset($this->factories['databaseManager']) ? $this->factories['databaseManager'] : null;
315   }
316
317   /**
318    * Retrieve the module directory for this context.
319    *
320    * @return string An absolute filesystem path to the directory of the
321    *                currently executing module, if one is set, otherwise null.
322    */
323   public function getModuleDirectory()
324   {
325     // get the last action stack entry
326     if (isset($this->factories['actionStack']) && $lastEntry = $this->factories['actionStack']->getLastEntry())
327     {
328       return sfConfig::get('sf_app_module_dir').'/'.$lastEntry->getModuleName();
329     }
330   }
331
332   /**
333    * Retrieve the module name for this context.
334    *
335    * @return string The currently executing module name, if one is set,
336    *                otherwise null.
337    */
338   public function getModuleName()
339   {
340     // get the last action stack entry
341     if (isset($this->factories['actionStack']) && $lastEntry = $this->factories['actionStack']->getLastEntry())
342     {
343       return $lastEntry->getModuleName();
344     }
345   }
346
347   /**
348    * Retrieve the request.
349    *
350    * @return sfRequest The current sfRequest implementation instance.
351    */
352   public function getRequest()
353   {
354     return isset($this->factories['request']) ? $this->factories['request'] : null;
355   }
356
357   /**
358    * Retrieve the response.
359    *
360    * @return sfResponse The current sfResponse implementation instance.
361    */
362   public function getResponse()
363   {
364     return isset($this->factories['response']) ? $this->factories['response'] : null;
365   }
366
367   /**
368    * Set the response object.
369    *
370    * @param sfResponse $response  An sfResponse instance.
371    *
372    * @return void
373    */
374   public function setResponse($response)
375   {
376     $this->factories['response'] = $response;
377   }
378
379   /**
380    * Retrieve the storage.
381    *
382    * @return sfStorage The current sfStorage implementation instance.
383    */
384   public function getStorage()
385   {
386     return isset($this->factories['storage']) ? $this->factories['storage'] : null;
387   }
388
389   /**
390    * Retrieve the view cache manager
391    *
392    * @return sfViewCacheManager The current sfViewCacheManager implementation instance.
393    */
394   public function getViewCacheManager()
395   {
396     return isset($this->factories['viewCacheManager']) ? $this->factories['viewCacheManager'] : null;
397   }
398
399   /**
400    * Retrieve the i18n instance
401    *
402    * @return sfI18N The current sfI18N implementation instance.
403    */
404   public function getI18N()
405   {
406     if (!sfConfig::get('sf_i18n'))
407     {
408       throw new sfConfigurationException('You must enable i18n support in your settings.yml configuration file.');
409     }
410
411     return $this->factories['i18n'];
412   }
413
414   /**
415    * Retrieve the routing instance.
416    *
417    * @return sfRouting The current sfRouting implementation instance.
418    */
419   public function getRouting()
420   {
421     return isset($this->factories['routing']) ? $this->factories['routing'] : null;
422   }
423
424   /**
425    * Retrieve the user.
426    *
427    * @return sfUser The current sfUser implementation instance.
428    */
429   public function getUser()
430   {
431     return isset($this->factories['user']) ? $this->factories['user'] : null;
432   }
433
434   /**
435    * Returns the configuration cache.
436    *
437    * @return sfConfigCache A sfConfigCache instance
438    */
439   public function getConfigCache()
440   {
441     return $this->configuration->getConfigCache();
442   }
443  
444   /**
445    * Returns true if the context object exists (implements the ArrayAccess interface).
446    *
447    * @param  string $name The name of the context object
448    *
449    * @return Boolean true if the context object exists, false otherwise
450    */
451   public function offsetExists($name)
452   {
453     return $this->has($name);
454   }
455
456   /**
457    * Returns the context object associated with the name (implements the ArrayAccess interface).
458    *
459    * @param  string $name  The offset of the value to get
460    *
461    * @return mixed The context object if exists, null otherwise
462    */
463   public function offsetGet($name)
464   {
465     return $this->get($name);
466   }
467
468   /**
469    * Sets the context object associated with the offset (implements the ArrayAccess interface).
470    *
471    * @param string $offset The parameter name
472    * @param string $value The parameter value
473    */
474   public function offsetSet($offset, $value)
475   {
476     $this->set($offset, $value);
477   }
478
479   /**
480    * Unsets the context object associated with the offset (implements the ArrayAccess interface).
481    *
482    * @param string $offset The parameter name
483    */
484   public function offsetUnset($offset)
485   {
486     unset($this->factories[$offset]);
487   }
488
489   /**
490    * Gets an object from the current context.
491    *
492    * @param  string $name  The name of the object to retrieve
493    *
494    * @return object The object associated with the given name
495    */
496   public function get($name)
497   {
498     if (!$this->has($name))
499     {
500       throw new sfException(sprintf('The "%s" object does not exist in the current context.', $name));
501     }
502
503     return $this->factories[$name];
504   }
505
506   /**
507    * Puts an object in the current context.
508    *
509    * @param string $name    The name of the object to store
510    * @param object $object  The object to store
511    */
512   public function set($name, $object)
513   {
514     $this->factories[$name] = $object;
515   }
516
517   /**
518    * Returns true if an object is currently stored in the current context with the given name, false otherwise.
519    *
520    * @param  string $name  The object name
521    *
522    * @return bool true if the object is not null, false otherwise
523    */
524   public function has($name)
525   {
526     return isset($this->factories[$name]);
527   }
528
529   /**
530    * Listens to the template.filter_parameters event.
531    *
532    * @param  sfEvent $event       An sfEvent instance
533    * @param  array   $parameters  An array of template parameters to filter
534    *
535    * @return array   The filtered parameters array
536    */
537   public function filterTemplateParameters(sfEvent $event, $parameters)
538   {
539     $parameters['sf_context']  = $this;
540     $parameters['sf_request']  = $this->factories['request'];
541     $parameters['sf_params']   = $this->factories['request']->getParameterHolder();
542     $parameters['sf_response'] = $this->factories['response'];
543     $parameters['sf_user']     = $this->factories['user'];
544
545     return $parameters;
546   }
547  
548   /**
549    * Calls methods defined via sfEventDispatcher.
550    *
551    * If a method cannot be found via sfEventDispatcher, the method name will
552    * be parsed to magically handle getMyFactory() and setMyFactory() methods.
553    *
554    * @param  string $method     The method name
555    * @param  array  $arguments  The method arguments
556    *
557    * @return mixed The returned value of the called method
558    *
559    * @throws <b>sfException</b> if call fails
560    */
561   public function __call($method, $arguments)
562   {
563     $event = $this->dispatcher->notifyUntil(new sfEvent($this, 'context.method_not_found', array('method' => $method, 'arguments' => $arguments)));
564     if (!$event->isProcessed())
565     {
566       $verb = substr($method, 0, 3); // get | set
567       $factory = strtolower(substr($method, 3)); // factory name
568
569       if ('get' == $verb && $this->has($factory))
570       {
571         return $this->factories[$factory];
572       }
573       else if ('set' == $verb && isset($arguments[0]))
574       {
575         return $this->set($factory, $arguments[0]);
576       }
577
578       throw new sfException(sprintf('Call to undefined method %s::%s.', get_class($this), $method));
579     }
580
581     return $event->getReturnValue();
582   }
583
584   /**
585    * Execute the shutdown procedure.
586    *
587    * @return void
588    */
589   public function shutdown()
590   {
591     // shutdown all factories
592     if($this->has('user'))
593     {
594       $this->getUser()->shutdown();
595       $this->getStorage()->shutdown();
596     }
597
598     if ($this->has('routing'))
599     {
600         $this->getRouting()->shutdown();
601     }
602
603     if (sfConfig::get('sf_use_database'))
604     {
605       $this->getDatabaseManager()->shutdown();
606     }
607
608     if (sfConfig::get('sf_logging_enabled'))
609     {
610       $this->getLogger()->shutdown();
611     }
612   }
613 }
614
Note: See TracBrowser for help on using the browser.