Reputation: 1951
I have a Laravel model that loads a resource from a remote SSH server, then stores the returned data in properties within the model. Here is a simplified version of my code:
SomeController.php (Controller)
$foo = new Foo();
$foo->load(52); // Load resource #52
echo 'The title of resource #52 is ' . $foo->getTitle();
Foo.php (Model)
class Foo extends Model
{
private $_id;
private $_title;
private $_body;
public function loadResource($id)
{
// ...connect to external SSH server and retrieve resource
$this->_id = $resource->id;
$this->_title = $resource->title;
$this->_body = $resource->body;
}
public function getTitle()
{
return $this->_title;
}
public function getBody()
{
return $this->_body;
}
}
Is there a better or more idiomatic way of structuring this, or some sort of pattern I should be following?
Is there a name for this type of class?
Is it an appropriate thing to place in a model?
Upvotes: 1
Views: 428
Reputation: 3045
You might use the "retrieved" model event to achieve that:
https://laravel.com/docs/5.8/eloquent#events
class Foo extends Model
{
public static function boot()
{
static::retrieved(function (Foo $foo) {
$foo->resource = getResource();
)
}
}
That's gonna bind the external resource to the resource property when the model is retrieved from the database:
$foo = Foo::find(100);
Then you are able to get resource attributes via the resource property from the model.
$foo->resource->id;
$foo->resource->title;
$foo->resource->body;
Upvotes: 1