Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Gamecock's avatar

How to call PHP Classes based on Models row names

I use Laravel as a web service that collect data from external websites using API. Every website, has a different api_key and endpoint url with completely different code strategy logics for returning data.

websites table

+----+----------+--------------------------------------------+-----------------------+
| id | name     | endpoint                                   | apikey                |
+----+----------+--------------------------------------------+-----------------------+
| 1  | Website1 | https://website1.com/stubs/handler_api.php | o8y3eygfd8gd     |
+----+----------+--------------------------------------------+-----------------------+
| 2  | Website2 | https://www.website2.com/api/              | 32165456151           |
+----+----------+--------------------------------------------+-----------------------+
| 3  | Website3 | https://www.website2.com/v2/api.php        | 978YAD7GA8D3Q |
+----+----------+--------------------------------------------+-----------------------+

Website1.php

class Website1 {

   getBooks(){
      //a logic for getting data.
   }
}

Website2.php

class Website2 {

   getBooks(){
      //another logic for getting data.
   }
}

Website.php Model

public function getBooks(){
   //How to call Website classes getBooks method based on $this->name ?
}

For example, how to call Website classes getBooks methods in getBooks Model method based on $this->name ? And how to access apikey and endpoints? Or where should I put these classes?

0 likes
3 replies
Snapey's avatar
Snapey
Best Answer
Level 122

create a table holding details for each service.

In the table, also hold the name of a class that can process that particular API format.

Do you access them all on the same frequency? If so, just get all the rows and loop through them, calling the relevant class and passing it the record which contains the endpoint and the credentials.

$sites = Website::get();

foreach($sites as $site) {
    
    $website = new $site->name($site);

    $website->getBooks;
}

change the name column to include the full namespace of the class

change the constructor of your class to accept the website details

1 like
Gamecock's avatar

@snapey Thanks. Where is the best place can I store these classes? And is it the best way in Laravel structure?

Snapey's avatar

wherever you like.

I would create a folder app/Collectors and set the namespace in the class to namespace App\Collectors

Please or to participate in this conversation.