<?php
class Client extends Eloquent {
protected $table = 'clients';
private $connection = 'connection2';
public function getById($id) {
return DB::connection($this->connection)->table('clients')
->select('client_name')
->where('id', $id)
->first();
}
}
This model needs to connect to different connection than usuall in this application. At first I was giving connection string to function as parameter, but later decided that its not good to pass same parameter over and over again, when I know that for this model only this connection will be used. Now it is hard coded as private variable.
And there are several such models with same connection. Its ok, but it could be better if this connection setting would be in one place, in case it is changed - so then no need to go though all models which use this and change.
So one thing comes to mind is to have some parent model with this connection and Client model extends from it.
But not sure if that would be good? Maybe you have some other ideas?
Create a seperate class that defines the connection and in the future extend any classes with this class.
use Eloquent;
class Connection2Eloquent extends Eloquent
{
protected $connection = "connection2";
}
now extend your client with connection2eloquent:
class Client extends Connection2Eloquent
{
}
Related
Everytime I'm writing a Laravel model it just gives me a feeling of messy code. I have relationships and other model functions specially when using domain driven design. So I though about separating relationships and functions.
Example I have a User class that extends Eloqeunt:
class User extends Eloquent{}
and inside this class I have register functions and password hashing functions etc. Also, we can declare the relationships so:
class User extends Eloquent{
function post(){
return $this->hasMany('POST');
}
}
For some reason this smells funky to me. My solution was to create a Entities folder and inside create a User folder which will hold 2 files one would be UserRelationship which would hold of the the relationships for this class:
class UserRelationship extends Eloquent{
function post(){
return $this->hasMany('POST');
}
}
and a second which would be the actual User class where I would write all of the functions and this class would extend the UserRelationship class instead of Eloquent:
class User extends UserRelationship{
public static function register($email, $password, $activate_token)
{
$user = new static(compact('email', 'password', 'activate_token'));
$user->raise(new UserWasRegistered($user));
return $user;
}
}
What do you guys think of this approach I am relatively new to all this so I don't know if this is bad practice or to much work for little reward. What do you guys recommend?
For a user model, it is too much work. The easiest way and still a better approach is to define the relationship in the user model. If for example it is a post model where you have relationships for post to "user, comment, reply etc" then you can attempt splitting your relationships
I've read and followed documentation found here http://laravel.com/docs/eloquent
and I tried some of the examples i found here
here is the code that I have so far
model
dbeloquent.php
<?php
class dbeloquent extends Eloquent {
protected $table = "users";
public function showTbl()
{
dd(dbeloquent::$table);
}
}
//end of model
?>
route.php
<?php
Route::get('/', function () {
$model = new dbeloquent();
dd($model->someFunction());
});
?>
I want to show my tables first but here is what I'm having
Access to undeclared static property: dbeloquent::$table
somebody help me please
Your dbeloquent class is extending Model class in the background. Eloquent alias is pointing to Model class, in the app/config/app.php file
'Eloquent' => 'Illuminate\Database\Eloquent\Model'
protected $table property is extended from the abstract Model class, and it is not static, so you can't redeclare it (static or nostatic) .The way you can access property from base model is by using:
__get($key) method
But the problem is in which point of execution your $table property is visible, since it is protected and modified at run time.
At the end, it is not declared and defined to be used in such a way - Laravel is internally looking for that property. Try to trace calls, and you will probably find what is happening inside.
Don't complicate things more then they should be complicated.
I have two database connections, one that is used for most of my application data, and one that is only used for reads.
Although I can setup my database user account to only allow reads, there are other people administering this system, and I want some redundancy at the application level to absolutely prevent unintended writes using the Yii's standard ActiveRecord classes.
Found this bit of information on the forums, but was wondering if someone could confirm that this is a good approach and/or suggest another one.
public function onBeforeSave($event)
{
$this->db = Yii::app()->masterDb;
}
public function onAfterSave($event)
{
$this->db = Yii::app()->db;
}
http://www.yiiframework.com/forum/index.php/topic/5712-active-record-save-to-different-server-load-balancefail-over-setup/
Per that link you provided to the Yii forums, there's an extension that handles this for you:
http://www.yiiframework.com/extension/dbreadwritesplitting
I'd probably look into that first, if you've got a lot of AR models. You could go the Behavior route (as suggested in that forum post) as another option.
But whatever you do, you are going to want to be overriding beforeSave / afterSave instead of onBeforeSave / onAfterSave. Those methods are for triggering events, not just running your own special code. And, per another one of the forum posts, you'll need to set your AR db variable using a static call. So Sergey's code should actually be:
class MyActiveRecord extends CActiveRecord
{
...
public function beforeSave()
{
// set write DB
self::$db = Yii::app()->masterDb;
return parent::beforeSave();
}
public function afterSave()
{
// set read db
self::$db = Yii::app()->db;
return parent::beforeSave();
}
...
}
class User extends MyActiveRecord {}
class Post extends MyActiveRecord {}
...
Given a scenario where your slave can't update with the master, you might run into problems.
Because after updating data you'll maybe read from an old version.
While the given approaches in the forum are very clean and written by authors which are mostly Yii wizards. I also have an alternative. You may override the getDbConnection() method in AR like
public function getDbConnection(){
if (Yii::app()->user->hasEditedData()) { # you've got to write something like this(!)
return Yii::app()->masterDb;
} else {
return Yii::app()->db;
}
}
But you still have to be careful when switching database connections.
class MyActiveRecord extends CActiveRecord
{
...
public function onBeforeSave($event)
{
// set write DB
$this->db = Yii::app()->masterDb;
}
public function onAfterSave($event)
{
// set read db
$this->db = Yii::app()->db;
}
...
}
class User extends MyActiveRecord {}
class Post extends MyActiveRecord {}
...
You have to try that way. But in my opinion, it's not good enough. I think there will be some bugs or defects.
I am administering a system which is fairly old. It is a code soup at the moment and bit by bit I have been refactoring the code.
Something I noticed while doing this was that 90% of the queries were CRUD. No joins, nothing else. All really simple stuff.
As a result I created a model class which cover's these types of query's. I then extend the model class for each table.
class Model extends MySQLi {
public function __construct() {
global $site;
$mysql = $site['mysql'];
parent::__construct($mysql['host'], $mysql['user'], $mysql['pass'], $mysql['db']);
}
I don't like the use of the global but it does allow me to do this without having to worry about connection details.
<?php
class Contact extends Model {
public $table = 'contact';
}
$Contact = new Contact;
$Contact->get(array('where'=>array('id >' => 4), 'limit' => array(0, 20));
My concern is that if a script requires 3 tables. I will be using 3 models and thus surely that means I will have 3 independent database connections? One for each class?
Is this going to be a problem like I think it will be?
Is there a work around which will allow me to continue to extend MySQLi and maybe pass it an active connection instead of connection details for it to make its own connection?
Do not extend Mysqli, just contain it in your model.
class Model {
protected $db;
public function __construct($db) {
$this->db = $db; // the mysqli instance.
}
.....
}
I use Capsule to manage database connections in my project, and use Model to operate databases, like this:
// Init Eloquent ORM Connection
$capsule = new Capsule;
$capsule->addConnection(Config::getDbConfig());
$capsule->addConnection(Config::getRadiusDbConfig(), 'radius');
$capsule->bootEloquent();
I want to use transaction while executing a large modification to database, but there're no related methods in the class Model.
Because of the Capsule, I'm not able to use Illuminate\Suooprt\Facades\DB , since it reports this error:
PHP Fatal error: Uncaught RuntimeException: A facade root has not been set. in
E:\Projects\ss-panel\vendor\illuminate\support\Facades\Facade.php:210
How should I deal with it?
I am using Eloquent ORM outside Laravel.
Here is the solution how I start transaction.
You can add an base model extend \Illuminate\Database\Eloquent\Model.
<?php
use Illuminate\Database\Eloquent\Model as EloquentModel;
class Model extends EloquentModel
{
public static function beginTransaction()
{
self::getConnectionResolver()->connection()->beginTransaction();
}
public static function commit()
{
self::getConnectionResolver()->connection()->commit();
}
public static function rollBack()
{
self::getConnectionResolver()->connection()->rollBack();
}
}
Then, you can use it like this:
Model::beginTransaction();
//do what you like.
Model::commit();
// OR
Model::rollBack();