sorry for my english.
stack: Slim 3 framework + Eloquent ORM. Eloquent works as expected with Slim.
I want to use sort of a MVC pattern where thin controllers and fat models(all db queries and other heavy logic).
All I found is how to use it from routes like this:
$app->get('/loans', function () use ($app) {
$data = DB::table('loan_instalment')->get(); // works
$data = $this->db->table('loan_instalment')->get(); // works
...
}
What I want is ability to call public methods from choosen model, something like this:
use \src\models\Instalment;
$app->get('/loans', function () use ($app) {
$data = $this->model('Instalment')->getSomething(12);
...
}
and Model class is:
namespace src\models;
use Illuminate\Database\Eloquent\Model as Model;
use Illuminate\Database\Capsule\Manager as DB;
class Instalment extends Model
{
protected $table = 'loan_instalment';
public function getSomething($id)
{
return $this->table->find($id);
}
// bunch of other methods
}
My app looks like basic Slim skeleton, Eloquent settings:
$capsule = new \Illuminate\Database\Capsule\Manager;
$capsule->addConnection($container['settings']['db']);
$capsule->setAsGlobal();
$capsule->bootEloquent();
$container['db'] = function ($container) use ($capsule){
return $capsule;
};
Is it possible ?
You could use the abbility of Slim to use controllers.
Make a basic controller:
and then in your controllers extend this class and add it to the slim container
Another possibility is to extend your \Slim\App by:
I actually would advice against these both methods, and not load your models in this way, since this is considered bad practice.
It is better just to use:
If you want to use MVC pattern, you need to make base controller.
And the container:
Highly recommended to use static function on models
And now you code become:
The controller:
And the route for the controller
It looks cleaner, isn't it?
More tutorial: