【问题标题】:Use external class library as model class for Laravel使用外部类库作为 Laravel 的模型类
【发布时间】:2020-10-21 15:48:49
【问题描述】:

我是 Laravel 和 PHP 的新手。

我编写了一个标准的 PHP 库,它定义了一个 GpxWaypoint 类。该类声明了一些属性(纬度、经度、海拔、名称)并定义了一些方法(getDistance($anotherWaypoint)、getAscent($anotherWaypoint)),显然没有扩展 Eloquent Model 类。

class GpxWaypoint
{
    private $latitude;      
    private $longitude;     
    .......

然后我写了一个测试 Laravel 中的 Waypoint 类,具有与标准 GpxWaypoint 类相同的属性。

class Waypoint extends Model
{

   public function user()
    {
        return $this->belongsTo(User::class);
    }
}
class CreateWaypointsTable extends Migration
{
    public function up()
    {
        Schema::create('waypoints', function (Blueprint $table) {
            $table->id();
            $table->string('name', 128);
            $table->decimal('latitude', 32, 28);
            $table->decimal('longitude', 32, 28);
            $table->integer('altitude');
            $table->timestamps();
        });
    }

有没有办法将外部库中定义的 GpxWaypoint 类用作 Laravel 模型类? 在 composer.json 中,我将外部库添加为必需的库并运行,我可以实例化 GpxWaypoints 对象...但我不知道如何将其用作模型类。

我想使用 GpxWaypoint 类,因为它定义了我在 Laravel 项目中需要的一些方法和功能,我不想重写它们(外部库还包含 GpxFile、GpxTrack、GpsTrackSegment、GpsTrackPoint 类及其属性以及我也想在我的 Laravel 项目中使用的方法)

谢谢

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

    这两个类实际上是完全不同的。 GpxWaypoint 具有成员变量,而 Waypoint 由数据库属性支持。尝试混合这两个概念并不是一个好主意,因为 Laravel 内部对属性的访问方式不同。

    我建议将共享概念提取为特征,例如:

    trait WaypointTrait {
       public getDistance($anotherWaypoint) {
         ...
       }
    
    }
    
    class GpxWaypoint
    {
        use WaypointTrait;
     
        private $latitude;      
        private $longitude;     
        .......
    
    }
    class Waypoint extends Model
    {
       use WaypointTrait;
    
    }
    

    【讨论】:

    • 非常好的解决方案。测试成功。非常感谢!!!
    猜你喜欢
    • 2017-05-09
    • 2019-02-09
    • 2020-09-20
    • 2016-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多