0

I am getting confused on how to use a meddo config class

$database = new Medoo([
    'database_type' => 'mysql',
    'database_name' => 'name',
    'server' => 'localhost',
    'username' => 'your_username',
    'password' => 'your_password',
]);

inside another class

class Blog {
    public function getBlogs(){
       return $database->select('post', "title");
    }
}

Right now i am using globals to work around is their any direct way that I may use.

I don't want to use it like this

<?php
include 'classes/config.php';

class blog{


function A(){
    global $database;
    return $database->select('post', "title");
    }
}


function B(){
    global $database;
    return $database->select('post', "title");
    }
}


function C(){
    global $database;
    return $database->select('post', "title");
    }
}


?>

2 Answers2

0

Try this by passing the $database in __construct() and then assign $database to class private variable

include 'config.php';
class blog{
    private $database = null;

    function __construct($db)
    {
        $this->database = $db;
    }

    function A(){
        $this->database->select('post', "title");
    }
}

$obj = new blog($database);
$obj->A();
Vinay Patil
  • 736
  • 6
  • 19
0

You can use use keyword to reference the database object for the function.

https://www.php.net/manual/en/functions.anonymous.php

$database = new Medoo();

class Blog {

    public get() use ($database) {
        return $database->select('post', "title");
    }
}

Or using singleton pattern that officially recommended.

https://medoo.in/api/collaboration

Angolao
  • 986
  • 1
  • 15
  • 27