2
votes

My "mvc_posts" table:

  • id (int)
  • title (varchar)
  • CATEGORY (varchar) -> example: 1,2,3
  • url (varchar)

My "mvc_categories" table:

  • id (id)
  • name (varchar)

My Post model class:

class Post extends Database{

    protected $table = 'mvc_posts';

    public function __construct(){
        $this->db = new Database;
    }

    public function viewByUrl($url){

        $obj = array();
        $where = array('url' => $url);
        $obj = $this->db->select("*", $this->table, $where);
        if($obj == true){

            $obj->category_name = $this->category->getName($obj->category);
            return $obj;

        }

    }

}

My Category model class:

class Category extends Database{

    protected $table = 'mvc_categories';

    public function __construct(){
        $this->db = new Database;
    }

    public function getName($category){

        $categories = explode(",", $category);
        $category_name = "";

        foreach($categories as $key => $value){

            $where = array('id' => $value);
            $category = $this->db->select("*", $this->table, $where);
            $category_name .= $category->name.', ';

        }
        return rtrim($category_name, ', ');

    }

}

How do I use the getName() method of the class Category in class Post?

1

1 Answers

0
votes

The simplest way would be to pass the Category model as parameter to Post::viewByUrl()

Although, most frameworks implement some form of dependency injection. Are you using a framework?