Php 具有Phalcon模型的名称空间

Php 具有Phalcon模型的名称空间,php,phalcon,Php,Phalcon,我使用命令phalcon project simple--type=simple创建了一个项目 我根本没有改变结构 让我感到困惑的是,我有两个数据库 我想访问数据库A和B的帐户模型,而不需要执行类似$Account=AAccount::find()的操作和$account=BAccount::find() 我目前有以下代码: model/AAccount.php class AAccount extends Phalcon\Mvc\Model { // use DB A } class

我使用命令
phalcon project simple--type=simple
创建了一个项目

我根本没有改变结构

让我感到困惑的是,我有两个数据库

我想访问数据库AB帐户模型,而不需要执行类似
$Account=AAccount::find()的操作
$account=BAccount::find()

我目前有以下代码:

model/AAccount.php

class AAccount extends Phalcon\Mvc\Model {
    // use DB A
}
class BAccount extends Phalcon\Mvc\Model {
    // use DB B
}
model/BAccount.php

class AAccount extends Phalcon\Mvc\Model {
    // use DB A
}
class BAccount extends Phalcon\Mvc\Model {
    // use DB B
}

这样做的最佳方式是什么?名称空间?我无法同时更改表名帐户

我不知道是否理解您的问题:您有两个名称相同的表,但它们位于两个不同的模式(数据库)中?如果是,我也遇到了同样的问题,我用以下结构解决了它(您可以在我的中看到这段代码的一部分)(也请参见此参考:):

(1) 基本模型类位于
模型/

namespace MyApp\Model;

class Base extends \Phalcon\Mvc\Model
{
     // code for your model base class
}
(2) 模式A的基类位于
模型/schema-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`;
    }

    // ...
}
namespace MyApp\Model\SchemaA;

class Account extends Base
{
    // ...
}
(3) 模式B的基类位于
模型/schema-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`;
    }

    // ...
}
namespace MyApp\Model\SchemaB;

class Account extends Base
{
    // ...
}
(4) 模式A中的帐户模型位于
模型/schema-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`;
    }

    // ...
}
namespace MyApp\Model\SchemaA;

class Account extends Base
{
    // ...
}
(5) 架构B中的帐户模型位于
模型/schema-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`;
    }

    // ...
}
namespace MyApp\Model\SchemaB;

class Account extends Base
{
    // ...
}
当您有固定数量的模式时,此解决方案效果良好,但是如果您没有固定数量的模式,我认为更好的解决方案是在模型库的
getSchema
函数中创建一个逻辑。比如:

public function getSchema()
{
    // this is just a suggest
    return $this->getDI()->scope->currentSchema;
}
我希望这能帮助你


注意:在使用名称空间的模型之间创建关系时必须小心。

绝对是名称空间。另外,如果您在文档中没有看到一个项目中的多个数据库+1表示名称空间。无论如何,使用它们都是一个好主意,但我以前有过完全相同的用例,没有任何障碍。@ShadMickelberry谢谢!我试试看。