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.
}
.....
}
Related
I am trying to get the php class Base to load only once for a custom MVC framework. So that i can close the database connection in the destructor and be able to use it in inheritance but I can't seem to figure it out. I looked at a singleton design here but i cant figure out how to load the database. Is there a way to get this working or perhaps a better way to do this. Or am i going about this in a totally stupid way and should change it?
Base class
class Base {
protected $db;
//constructor
public function Base(){
echo some unique id to test it worked
$db = connection to database
}
//load modules as needed
public function load($m){
$this->$m = new $m;
}
}
module class
class module extends Base {
//some random function
public function listing(){
$this->db->query();
}
}
the index.php which initializes the Base class
$main = new Base;
$main->load( 'module' );
$main->module->listing();
I am developing a eCommerce store for school project.
i have several classes like this that uses same database connection.
so i have to separate those.
1. how to use a single database connection file for all of my classes.I have sevaral classes same as this
2. I draw some use case and class diagram. if any one has experience in UML - (ecommerce ) can you verify those?
class abc {
public $id;
public $name;
public $email;
public $db;
function __construct()
{$this->db=new mysqli('localhost','root','','cart');}
public function newsletter_subcribe()
{$sql="insert into table (id,name,email) value('$this->id','$this->name','$this->email')";
$this->db->query($sql);}
this class is do some query to your database for CRUD, the best thing you can do is make one more controller to access to this class, also make sure every function to do that is in private, not public.
so basicly the controller will post data to class to do CRUD.
more like Model in CI.
CONTROLLER -->> YOUR CLASSS -->> DATABASE
CLASS A
{
private function dbconnection()
{
}
private function a($param)
{
dbconnection();
//CRUD HERE
}
}
CLASS B
main function()
{
//load class A here, and you can access all method
$result = a($param);
}
I'm playing around with Slim PHP framework and stumbled upon a situation I cannot work out.
First, I'll explain the basic setup:
Using slim-skeleton, I have a dependencies.php file, where the DIC is set up. It's the default slim-skeleton's setup with two more things:
$container['db'] = function ($c) {
return new PDO('mysql:host=localhost;dbname=****', '********', '********');
};
$container['model.user'] = function ($c) {
$db = $c['db'];
return new Dash\Models\User($db);
};
So, as you can see, I have two new things registered in the DIC - A PDO object and a User object.
But passing a database object for each and every other model is a bit of a pain... I would like to be able to inject the PDO object to a parent class, called Model.
So the Model should look like this:
class Model
{
protected $db;
public function __construct($db)
{
$this->db = $db;
}
}
And the User model:
class User extends Model
{
public function getById($id)
{
$this->db->... // I have access to the database object (PDO) from the parent class.
}
}
The thing is that I cannot have a parent object, because the slim's container returns a new instance of User and does not instantiate the parent Model class.
Any ideas on how to achieve inheritance, using Slim's container in a clean and usable way?
Thanks in advance.
That's not how inheritance works. User is an instance of Model. So when you do new User($c['db']), it'll work fine.
<?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
{
}
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.