Alvaro
Alvaro

Reputation: 41595

Where to place common functions for Models in Laravel

I'm quite new to Laravel. I have no DB connection but I'm trying to separate the logic in the Controllers placing it in the Model in order to create fat models and slim controllers.

When doing it I realized I have to make use of common functions in different models. I've seen they usually place those classes in a app\lib\, but I guess that's just for controllers to access them? I can not seem to access them from m model:

<?php
//in app/lib/MyLog.php
class MyLog{
  //whatever
}

Then in m model:

//in a model
MyLog::setLogApi($url);

The error I'm getting:

PHP Fatal error: Class 'MyLog' not found in C:\inetpub\wwwroot\laravel\app\models\Overview.php on line 80

Upvotes: 1

Views: 1643

Answers (3)

Sulthan Allaudeen
Sulthan Allaudeen

Reputation: 11310

If you include your Model like this in your Controller use App\MyLog;

Then You should have the MyLog.php file inside app\MyLog.php

Update : As the OP wants to access some common functions from any Model

Then Mutators should help you do that

Here is the similar example given over there

public function convertToLower($value)
    {
        $this->attributes['yourLowerString'] = strtolower($value);
    }

Upvotes: 1

J&#225;n Kyselica
J&#225;n Kyselica

Reputation: 699

You should use namespaces, it's good practice for modern PHP.

File app/lib/MyLog.php

namespace App\Lib;
class MyLog {
   // class functions
}

File /app/models/Overview.php

namespace App\Models;
use App\Lib\MyLog;
class Overview {
    // class functions
}

You can use short aliases for fully namespaced classes. Aliases are stored in /app/config/app.php, find part

"aliases" => array( 
     'App'               => 'Illuminate\Support\Facades\App',
     .
     .
     . );

At the end of array add your new alias for MyLog class:

'MyLog' => 'App\Lib\MyLog'

And now in your /app/models/Overview.php you can use shorter alias:

namespace App\Models;
use MyLog;
class Overview {
    // class functions
}

Upvotes: 0

Jack Sierkstra
Jack Sierkstra

Reputation: 1434

Ensure that your model has a namespacing. If your MyLog class has a namespace e.g.:

<?php namespace App\Logging;

class MyLog {

}

Then you can call that in your controller as follows:

<?php namespace App\Controllers;
use App\Logging\MyLog as MyLog;

class MyController {
  protected $logger;
  public function __construct() {
    $this->logger = new MyLog;
  }
}

It could be possible that you have to do a composer dump-autoload. This maps namespaces and classes to the right files.

Upvotes: 0

Related Questions