Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Namespaces with Phalcon models

Tags:

php

phalcon

I have a project made with the command phalcon project simple --type=simple.

I haven't changed the structure at all.

The part where I'm stumped, is that I have two databases I look at.

I want to access the Account model for both databases A and B, with out doing something like $account = AAccount::find(); and $account = BAccount::find();.

I currently have this code:

model/AAccount.php

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

model/BAccount.php

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

What is the most optimum way of doing so? Namespaces? I cannot change the table name Account for both.

like image 953
Naoto Ida Avatar asked Aug 22 '26 12:08

Naoto Ida


1 Answers

I don't know if I understand your question: you have two tables with the same name, but they are in two different schemas (databases)? If yes, I had the same problem and I solve it with the follow structure (you can see part of this code in my bauhaus project) (see this reference too: point to other schema (Phalcon - Working with Model)):

(1) Base model class located at models/:

namespace MyApp\Model;

class Base extends \Phalcon\Mvc\Model
{
     // code for your model base class
}

(2) Base class for schema A located at 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) Base class for schema B located at 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) Account Model in the schema A located at models/schema-a/:

namespace MyApp\Model\SchemaA;

class Account extends Base
{
    // ...
}

(5) Account Model in the schema B located at models/schema-b/:

namespace MyApp\Model\SchemaB;

class Account extends Base
{
    // ...
}

This solution works good when you have a fixed number of schemas, but If you have no-fixed number of schemas, I think a better solution would be to create an logic in the getSchema function of the model base. Something like:

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

I hope this can help you.

Note: you will have to be careful to create relationships between models with namespace.

like image 152
Fefas Avatar answered Aug 24 '26 01:08

Fefas