Namespaces with Phalcon Models
I have a project with a team 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'm looking at.
I want to access the Model Account for both databases A and B without 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's the best way? Namespaces? I cannot change the name of the Account table for both.
source to share
I don't know if I understand your question: do 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 following structure (you can see some of this code in my bauhaus project ) (see this link too: points to another schema (Phalcon - Working with the model) ):
(1) Base model class located in models/
:
namespace MyApp\Model;
class Base extends \Phalcon\Mvc\Model
{
// code for your model base class
}
(2) Base class for Scheme 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 scheme 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) An account model in Schema A located in models/schema-a/
:
namespace MyApp\Model\SchemaA;
class Account extends Base
{
// ...
}
(5) Account Model in Scheme B located in models/schema-b/
:
namespace MyApp\Model\SchemaB;
class Account extends Base
{
// ...
}
This solution works well when you have a fixed number of circuits , but if you don't have a fixed number of circuits, I think that the best solution would be to create the logic in getSchema
the base model function. Something like:
public function getSchema()
{
// this is just a suggest
return $this->getDI()->scope->currentSchema;
}
Hope this helps you.
Note. You have to be careful to create relationships between namespaced models.
source to share