[英]Whats the best way to create an array of objects inside a class as attribute in PHP?
所以我很難找出最好的方法和正確的方法,所以如果有人可以在這里幫助我,我會發布這個問題,因為我正在 PHP 中做一個 Laravel 項目。
假設我們正在為書籍構建一個應用程序,每本書有幾頁,有些有 20 頁,有些可能有 700 頁,如果我們要為這些書籍正確創建 class 或類,我們該怎么做?
下面我有幾種方法來 go 關於它,但我不知道什么會起作用,和/或什么是最好的。
選項1:
<?php
namespace Translation/Logic;
public class Book {
// atributes
public $title;
public $year;
public $author;
public $description;
public $date;
public $language = "English";
// as an atribute maybe we need to have an array of pages here? like
// public $pages = Pages[]??
}
public class Pages {
public number;
public orientation;
public direction;
public page;
public chapter;
public content;
}
選項 2:
<?php
namespace Translation/Logic;
abstract class Book {
// atributes
public $title;
public $year;
public $author;
public $description;
public $date;
public $language = "English";
// as an attributes maybe we need to have an array of pages here?
}
public class Pages extends Book {
public number;
public orientation;
public direction;
public page;
public chapter;
public content;
}
// Then create an array of Pages here, but then we have all the attributes of the books in every page, which don't really make sense?
我很確定我在這里做錯了,有一種更聰明的方法可以做到這一點,但在這里只需要一點幫助。
如果它是我的解決方案之一,應該完成我的代碼的代碼是什么,除了我的之外還有其他替代方法,每種方法的優缺點是什么。
如果不是,我錯了,那么定義這些類的正確方法是什么,為什么?
感謝您花時間回答我:)
正如蒂姆劉易斯在對他的問題的評論中所說,最好的方法是使用 Eloquent 模型。
讓我給你一個簡單的例子,說明如何做到這一點的最佳方式。
這將是他的書 class 。
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Book extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['title', 'year', 'author', 'description', 'date', 'language'];
/**
* Get the pages of this book.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function pages()
{
return $this->hasMany('App\Page');
}
}
這將是他的頁面 class 。
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Page extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['number', 'orientation', 'direction', 'page', 'date', 'chapter', 'content'];
/**
* Get the book of this page.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function book()
{
return $this->belongsTo('App\Book');
}
}
因此,如果您想獲得所有頁面的所有書籍,則必須像這樣在 controller 中進行。
$books = Book::with('pages')->get();
如果你只是想用你的頁面得到一本書。
$book = Book::with('pages')->first();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.