我可能不理解一些非常基本的东西。
Tim正在制作一个使用Sessions的假想应用程序,他很懒,希望使用现有的解决方案,而不是创建自己的解决方案。他发现了两个开发人员,John和Fabien,他们确切地拥有他需要的东西(但彼此不知道):
Fabien创建了2个类和1个接口
namespace Fabien;
interface SessionStorageInterface {
public function set($key, $val);
public function get($key);
}
class Storage implements SessionStorageInterface {
...
}
class Session {
public function __construct(SessionStorageInterface $storage){
...
}
}还有John,他创建了一个类和一个接口,与Fabien创建的接口相匹配
namespace John;
interface SessionStorageInterface {
public function set($key, $val);
public function get($key);
}
class Storage implements SessionStorageInterface {
...
}Tim认为John的Storage类比Fabien制作的类要好得多,并希望将其与Session类一起使用
$storage = new John\Storage;
$session = new Fabien\Session($storage);但这不起作用,因为Fabiens Session类只接受实现Fabien\SessionStorageInterface的类。
Tim如何将Fabien提供的Session类与John创建的Storage类结合使用?
发布于 2013-12-06 17:24:56
您可以在两个接口/实现之间添加一些胶水代码。
定义一个实现所需接口(A)的类,但在内部将方法调用委托给所需类(B)的实例。因此,您的中介adapter实例是A,但有B。
<?php
namespace Fabien {
interface SessionStorageInterface {
public function set($key, $val);
public function get($key);
}
class Storage implements SessionStorageInterface {
public function set($key, $val) {
echo 'enter ', __METHOD__, "\r\n";
$this->stg[$key] = $val;
}
public function get($key) {
echo 'enter ', __METHOD__, "\r\n";
return $this->stg[$key];
}
}
class Session {
public function __construct(SessionStorageInterface $storage){
echo 'enter ', __METHOD__, "\r\n";
$storage->set('foo', 'bar');
echo 'foo=', $storage->get('foo'), "\r\n";
}
}
}
namespace John {
interface SessionStorageInterface {
public function set($key, $val);
public function get($key);
}
class Storage implements SessionStorageInterface {
public function set($key, $val) {
echo 'enter ', __METHOD__, "\r\n";
$this->stg[$key] = $val;
}
public function get($key) {
echo 'enter ', __METHOD__, "\r\n";
return $this->stg[$key];
}
}
}
namespace Demo {
class StorageAdapter implements \Fabien\SessionStorageInterface {
protected $storageJohn = null;
public function __construct(\John\SessionStorageInterface $stg) {
$this->storageJohn = $stg;
}
public function set($key, $val) {
echo 'enter ', __METHOD__, "\r\n";
$this->storageJohn->set($key, $val);
}
public function get($key) {
echo 'enter ', __METHOD__, "\r\n";
$this->storageJohn->get($key);
}
}
function demo() {
echo 'enter ', __METHOD__, "\r\n";
$stg = new \John\Storage;
$session = new \Fabien\Session( new StorageAdapter($stg) );
}
demo();
}发布于 2013-12-06 17:06:11
他们不会。
与大多数其他编程语言一样,它们必须实现相同的接口(相同的!==相同的签名)。
他们还学习了每个文件一个类/一个接口的规则,以便那些想要从他们的代码中窃取一些东西的人可以轻松地完成事情。
https://stackoverflow.com/questions/20419836
复制相似问题