Development

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

You must first sign up to be able to contribute.

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

Revision 23810, 15.9 kB (checked in by Kris.Wallsmith, 4 years ago)

[1.3] set svn:eol-style property to native and svn:keywords property to Id on all .php files

  • 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   public function retrieveObjects($class, $peerMethod)
308   {
309     $retrievingClass = 'sf'.ucfirst(sfConfig::get('sf_orm', 'propel')).'DataRetriever';
310
311     return call_user_func(array($retrievingClass, 'retrieveObjects'), $class, $peerMethod);
312   }
313
314   /**
315    * Retrieve the database manager.
316    *
317    * @return sfDatabaseManager The current sfDatabaseManager instance.
318    */
319   public function getDatabaseManager()
320   {
321     return isset($this->factories['databaseManager']) ? $this->factories['databaseManager'] : null;
322   }
323
324   /**
325    * Retrieve the module directory for this context.
326    *
327    * @return string An absolute filesystem path to the directory of the
328    *                currently executing module, if one is set, otherwise null.
329    */
330   public function getModuleDirectory()
331   {
332     // get the last action stack entry
333     if (isset($this->factories['actionStack']) && $lastEntry = $this->factories['actionStack']->getLastEntry())
334     {
335       return sfConfig::get('sf_app_module_dir').'/'.$lastEntry->getModuleName();
336     }
337   }
338
339   /**
340    * Retrieve the module name for this context.
341    *
342    * @return string The currently executing module name, if one is set,
343    *                otherwise null.
344    */
345   public function getModuleName()
346   {
347     // get the last action stack entry
348     if (isset($this->factories['actionStack']) && $lastEntry = $this->factories['actionStack']->getLastEntry())
349     {
350       return $lastEntry->getModuleName();
351     }
352   }
353
354   /**
355    * Retrieve the request.
356    *
357    * @return sfRequest The current sfRequest implementation instance.
358    */
359   public function getRequest()
360   {
361     return isset($this->factories['request']) ? $this->factories['request'] : null;
362   }
363
364   /**
365    * Retrieve the response.
366    *
367    * @return sfResponse The current sfResponse implementation instance.
368    */
369   public function getResponse()
370   {
371     return isset($this->factories['response']) ? $this->factories['response'] : null;
372   }
373
374   /**
375    * Set the response object.
376    *
377    * @param sfResponse $response  An sfResponse instance.
378    *
379    * @return void
380    */
381   public function setResponse($response)
382   {
383     $this->factories['response'] = $response;
384   }
385
386   /**
387    * Retrieve the storage.
388    *
389    * @return sfStorage The current sfStorage implementation instance.
390    */
391   public function getStorage()
392   {
393     return isset($this->factories['storage']) ? $this->factories['storage'] : null;
394   }
395
396   /**
397    * Retrieve the view cache manager
398    *
399    * @return sfViewCacheManager The current sfViewCacheManager implementation instance.
400    */
401   public function getViewCacheManager()
402   {
403     return isset($this->factories['viewCacheManager']) ? $this->factories['viewCacheManager'] : null;
404   }
405
406   /**
407    * Retrieve the i18n instance
408    *
409    * @return sfI18N The current sfI18N implementation instance.
410    */
411   public function getI18N()
412   {
413     if (!sfConfig::get('sf_i18n'))
414     {
415       throw new sfConfigurationException('You must enable i18n support in your settings.yml configuration file.');
416     }
417
418     return $this->factories['i18n'];
419   }
420
421   /**
422    * Retrieve the routing instance.
423    *
424    * @return sfRouting The current sfRouting implementation instance.
425    */
426   public function getRouting()
427   {
428     return isset($this->factories['routing']) ? $this->factories['routing'] : null;
429   }
430
431   /**
432    * Retrieve the user.
433    *
434    * @return sfUser The current sfUser implementation instance.
435    */
436   public function getUser()
437   {
438     return isset($this->factories['user']) ? $this->factories['user'] : null;
439   }
440
441   /**
442    * Returns the configuration cache.
443    *
444    * @return sfConfigCache A sfConfigCache instance
445    */
446   public function getConfigCache()
447   {
448     return $this->configuration->getConfigCache();
449   }
450  
451   /**
452    * Returns true if the context object exists (implements the ArrayAccess interface).
453    *
454    * @param  string $name The name of the context object
455    *
456    * @return Boolean true if the context object exists, false otherwise
457    */
458   public function offsetExists($name)
459   {
460     return $this->has($name);
461   }
462
463   /**
464    * Returns the context object associated with the name (implements the ArrayAccess interface).
465    *
466    * @param  string $name  The offset of the value to get
467    *
468    * @return mixed The context object if exists, null otherwise
469    */
470   public function offsetGet($name)
471   {
472     return $this->get($name);
473   }
474
475   /**
476    * Sets the context object associated with the offset (implements the ArrayAccess interface).
477    *
478    * @param string $offset The parameter name
479    * @param string $value The parameter value
480    */
481   public function offsetSet($offset, $value)
482   {
483     $this->set($offset, $value);
484   }
485
486   /**
487    * Unsets the context object associated with the offset (implements the ArrayAccess interface).
488    *
489    * @param string $offset The parameter name
490    */
491   public function offsetUnset($offset)
492   {
493     unset($this->factories[$offset]);
494   }
495
496   /**
497    * Gets an object from the current context.
498    *
499    * @param  string $name  The name of the object to retrieve
500    *
501    * @return object The object associated with the given name
502    */
503   public function get($name)
504   {
505     if (!$this->has($name))
506     {
507       throw new sfException(sprintf('The "%s" object does not exist in the current context.', $name));
508     }
509
510     return $this->factories[$name];
511   }
512
513   /**
514    * Puts an object in the current context.
515    *
516    * @param string $name    The name of the object to store
517    * @param object $object  The object to store
518    */
519   public function set($name, $object)
520   {
521     $this->factories[$name] = $object;
522   }
523
524   /**
525    * Returns true if an object is currently stored in the current context with the given name, false otherwise.
526    *
527    * @param  string $name  The object name
528    *
529    * @return bool true if the object is not null, false otherwise
530    */
531   public function has($name)
532   {
533     return isset($this->factories[$name]);
534   }
535
536   /**
537    * Listens to the template.filter_parameters event.
538    *
539    * @param  sfEvent $event       An sfEvent instance
540    * @param  array   $parameters  An array of template parameters to filter
541    *
542    * @return array   The filtered parameters array
543    */
544   public function filterTemplateParameters(sfEvent $event, $parameters)
545   {
546     $parameters['sf_context']  = $this;
547     $parameters['sf_request']  = $this->factories['request'];
548     $parameters['sf_params']   = $this->factories['request']->getParameterHolder();
549     $parameters['sf_response'] = $this->factories['response'];
550     $parameters['sf_user']     = $this->factories['user'];
551
552     return $parameters;
553   }
554  
555   /**
556    * Calls methods defined via sfEventDispatcher.
557    *
558    * If a method cannot be found via sfEventDispatcher, the method name will
559    * be parsed to magically handle getMyFactory() and setMyFactory() methods.
560    *
561    * @param  string $method     The method name
562    * @param  array  $arguments  The method arguments
563    *
564    * @return mixed The returned value of the called method
565    *
566    * @throws <b>sfException</b> if call fails
567    */
568   public function __call($method, $arguments)
569   {
570     $event = $this->dispatcher->notifyUntil(new sfEvent($this, 'context.method_not_found', array('method' => $method, 'arguments' => $arguments)));
571     if (!$event->isProcessed())
572     {
573       $verb = substr($method, 0, 3); // get | set
574       $factory = strtolower(substr($method, 3)); // factory name
575
576       if ('get' == $verb && $this->has($factory))
577       {
578         return $this->factories[$factory];
579       }
580       else if ('set' == $verb && isset($arguments[0]))
581       {
582         return $this->set($factory, $arguments[0]);
583       }
584
585       throw new sfException(sprintf('Call to undefined method %s::%s.', get_class($this), $method));
586     }
587
588     return $event->getReturnValue();
589   }
590
591   /**
592    * Execute the shutdown procedure.
593    *
594    * @return void
595    */
596   public function shutdown()
597   {
598     // shutdown all factories
599     if($this->has('user'))
600     {
601       $this->getUser()->shutdown();
602       $this->getStorage()->shutdown();
603     }
604
605     if ($this->has('routing'))
606     {
607         $this->getRouting()->shutdown();
608     }
609
610     if (sfConfig::get('sf_use_database'))
611     {
612       $this->getDatabaseManager()->shutdown();
613     }
614
615     if (sfConfig::get('sf_logging_enabled'))
616     {
617       $this->getLogger()->shutdown();
618     }
619   }
620 }
621
Note: See TracBrowser for help on using the browser.