Kavi Siegel Kavi Siegel -4 years ago 79
PHP Question

Children classes sharing methods without running __construct multiple times

I have 5 different model classes. Each one handles different types of data, but they all follow the same format.

I want each kind of model to share functions like toJson, toArray, etc.

There's a bunch of hack ways I could do this, and I can figure those out, but there HAS TO be a better way.

Here's my desired effect:

something here{
function toJson(){return json_encode($this->lastResult);}
class applications{
function findAllFoo(){
$this->lastResult = $this->db->foo->find();
return $this;

class users{
function findAllBar(){
$this->lastResult = $this->db->bar->find();
return $this;
$models = new models();

echo $models->applications->findAllFoo()->toJson();
echo $models->users->findAllBar()->toJson();

I could just do
new applications($this)
passing the models each an entire set of classes, but I'm sure there's a way within standard practices to do this.

TL;DR - How do I have a set of classes that shares some helper functions, yet won't conflict with the

Answer Source

If all models share some functionality, why not have a "Model" base class for them?

abstract class Model {
    protected $lastResult;
    protected $db;

    public function __construct(DB $db) {
        $this->db = $db;

    public function toJson() {
        return json_encode($this->lastResult);

class Applications extends Model {
    public function findAllFoo() {
        $this->lastResult = $this->db->foo->find();
        return $this;

class ModelBroker {
    public $applications;

    public function __construct() {
        $db = /* ... connection code here ... */;
        $this->applications = new Applications($db); // <-- dependency injection

$models = new ModelBroker();
$json = $models->applications->findAllFoo()->toJson();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download