我正在尝试从控制器访问另一个命名空间中的模型中的方法,而我唯一能做到的是使该方法静态化。这是正确的方法吗?还是有任何更整洁的方法?
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Helpers\ConnectedHost;
class PagesController extends Controller
{
/*
* REMOVED CODE HERE FOR READABILITY
* Below is where I instantiate the "connectedHost"-object
*/
$hosts[$hostKey] = new ConnectedHost($hostAttributes['ipv4'], $hostAttributes['mac']);
}
/* REMOVED CODE HERE FOR READABILITY AS WELL */
namespace App\Helpers;
class ConnectedHost
{
public $ipv4, $mac;
public function __construct($ipv4, $mac)
{
$this->ipv4 = $ipv4;
$this->mac = $mac;
// This is where I call the getName-function staticly,
$this->name = \App\Host::getName();
}
}
namespace App;
use Illuminate\Database\Eloquent\Model;
class Host extends Model
{
// The method below is declared static
public static function getName()
{
$name = 'wenzzzel';
return $name;
}
}
答案 0 :(得分:1)
如果您要直接从类似模型的方法访问
$data = \App\ModelName::methodName();
然后您的方法应该是静态的。
如果您的方法不是静态的,则可以访问,
$model = new \App\ModelName();
$data = $model->methodName();