1: <?php
2: /**
3: * Wei Framework
4: *
5: * @copyright Copyright (c) 2008-2015 Twin Huang
6: * @license http://opensource.org/licenses/mit-license.php MIT License
7: */
8:
9: namespace Wei;
10:
11: /**
12: * The base class for all services
13: *
14: * @author Twin Huang <twinhuang@qq.com>
15: */
16: abstract class Base
17: {
18: /**
19: * The service provider map
20: *
21: * @var array
22: */
23: protected $providers = array();
24:
25: /**
26: * The service container object
27: *
28: * @var Wei
29: */
30: protected $wei;
31:
32: /**
33: * Constructor
34: *
35: * @param array $options The property options
36: * @throws \InvalidArgumentException When option "wei" is not an instance of "Wei\Wei"
37: */
38: public function __construct(array $options = array())
39: {
40: if (!isset($options['wei'])) {
41: $this->wei = Wei::getContainer();
42: } elseif (!$options['wei'] instanceof Wei) {
43: throw new \InvalidArgumentException(sprintf('Option "wei" of class "%s" should be an instance of "Wei\Wei"', get_class($this)), 1000);
44: }
45: $this->setOption($options);
46: }
47:
48: /**
49: * Set option property value
50: *
51: * @param string|array $name
52: * @param mixed $value
53: * @return $this
54: */
55: public function setOption($name, $value = null)
56: {
57: // Set options
58: if (is_array($name)) {
59: foreach ($name as $k => $v) {
60: $this->setOption($k, $v);
61: }
62: return $this;
63: }
64:
65: if (method_exists($this, $method = 'set' . $name)) {
66: return $this->$method($value);
67: } else {
68: $this->$name = $value;
69: return $this;
70: }
71: }
72:
73: /**
74: * Returns the value of option
75: *
76: * @param string $name The name of property
77: * @return mixed
78: */
79: public function getOption($name)
80: {
81: if (method_exists($this, $method = 'get' . $name)) {
82: return $this->$method();
83: } else {
84: return isset($this->$name) ? $this->$name : null;
85: }
86: }
87:
88: /**
89: * Invoke a service by the given name
90: *
91: * @param string $name The name of service
92: * @param array $args The arguments for the service's __invoke method
93: * @return mixed
94: */
95: public function __call($name, $args)
96: {
97: return call_user_func_array($this->$name, $args);
98: }
99:
100: /**
101: * Get a service object by the given name
102: *
103: * @param string $name The name of service
104: * @return $this
105: */
106: public function __get($name)
107: {
108: return $this->$name = $this->wei->get($name, array(), $this->providers);
109: }
110: }
111: