我用phalcon project simple --type=simple
命令做了一个项目。
我一点也没改变结构。
让我困惑的是,我有两个数据库。
我想访问数据库A和数据库B的帐户模型,而不需要执行类似$account = AAccount::find();
和$account = BAccount::find();
的操作。
我现在有这个代码:
型号/aaccount.php
class AAccount extends Phalcon\Mvc\Model {
// use DB A
}
模型/baccount.php
class BAccount extends Phalcon\Mvc\Model {
// use DB B
}
这样做的最佳方式是什么?名称空间?我不能同时更改表名帐户。
最佳答案
我不知道我是否理解您的问题:您有两个同名的表,但它们在两个不同的模式(数据库)中?如果是,我有同样的问题,我用下面的结构来解决它(您可以在我的bauhaus project中看到这段代码的一部分)(也可以参阅这个参考:point to other schema (Phalcon - Working with Model)):
(1)位于models/
的基本模型类:
namespace MyApp\Model;
class Base extends \Phalcon\Mvc\Model
{
// code for your model base class
}
(2)位于
models/schema-a/
的架构A的基类:namespace MyApp\Model\SchemaA;
class Base extends MyApp\Model\Base
{
// ...
// returns the name of the schema A
public function getSchema()
{
return `schema_a_name`;
}
// ...
}
(3)位于
models/schema-b/
的模式B的基类:namespace MyApp\Model\SchemaB;
class Base extends MyApp\Model\Base
{
// ...
// returns the name of the schema B
public function getSchema()
{
return `schema_b_name`;
}
// ...
}
(4)位于
models/schema-a/
的架构A中的帐户模型:namespace MyApp\Model\SchemaA;
class Account extends Base
{
// ...
}
(5)位于
models/schema-b/
的架构B中的帐户模型:namespace MyApp\Model\SchemaB;
class Account extends Base
{
// ...
}
当您有固定数量的模式时,这个解决方案很好,但是如果您没有固定数量的模式,我认为更好的解决方案是在模型库的
getSchema
函数中创建一个逻辑。类似于:public function getSchema()
{
// this is just a suggest
return $this->getDI()->scope->currentSchema;
}
我希望这能帮助你。
注意:您必须小心创建具有命名空间的模型之间的关系。
关于php - Phalcon模型的命名空间,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29840157/