【问题标题】:Namespaces with Phalcon modelsPhalcon 模型的命名空间
【发布时间】:2015-04-24 06:25:54
【问题描述】:

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

我根本没有改变结构。

我被难住的部分是,我查看了两个数据库。

我想访问数据库 ABAccount 模型,而不执行 $account = AAccount::find();$account = BAccount::find(); 之类的操作.

我目前有这个代码:

model/AAccount.php

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

model/BAccount.php

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

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

【问题讨论】:

  • 绝对是命名空间。此外,如果您还没有在一个项目中的多个数据库的文档中看到。 docs.phalconphp.com/en/latest/reference/…
  • +1 用于命名空间。无论如何,它们都是一个好主意,但我以前也有过完全相同的用例,没有遇到任何障碍。
  • @ShadMickelberry 谢谢!我试试看。

标签: php phalcon


【解决方案1】:

我不知道我是否理解您的问题:您有两个同名的表,但它们位于两个不同的模式(数据库)中?如果是,我遇到了同样的问题,我用以下结构解决了它(你可以在我的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) 架构 A 的基类位于 models/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`;
    }

    // ...
}

(3) 架构 B 的基类位于 models/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`;
    }

    // ...
}

(4) 架构A中的账户模型位于models/schema-a/

namespace MyApp\Model\SchemaA;

class Account extends Base
{
    // ...
}

(5) 架构 B 中的账户模型位于 models/schema-b/

namespace MyApp\Model\SchemaB;

class Account extends Base
{
    // ...
}

当您拥有固定数量的架构时,此解决方案效果很好,但如果您拥有不固定数量的架构,我认为更好的解决方案是创建模型库的getSchema 函数中的逻辑。比如:

public function getSchema()
{
    // this is just a suggest
    return $this->getDI()->scope->currentSchema;
}

希望对你有帮助。

注意:您必须小心在具有命名空间的模型之间创建关系。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-04
    • 2014-04-30
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 2012-09-10
    • 2011-08-16
    相关资源
    最近更新 更多