gpt4 book ai didi

php - 我应该使用数组还是对象

转载 作者:可可西里 更新时间:2023-11-01 07:58:23 25 4
gpt4 key购买 nike

首先我会说,是的,我搜索过这个...我正在阅读有关编程的书籍以增加我的知识。目前我还没有找到这个问题的答案。我的应用程序有一个可行的解决方案,但它看起来一团糟。这是 PHP。

情况:我正在创建一个应用程序,其中包含一个从数据库中的 3 个表中提取的动态菜单(食物):

menu_types:
id name
1 Bar
2 Kitchen
menu_categories:
id name type_id
1 Salads 2
2 Teas 1
3 Pastries 2

menu_items
id name cat_id description price image
1 Caesar 1 'hail Caesar' $5.00 'image location'
2 Greek 1 'Plato's fav' $3.00 'image location'
3 Cinnamon Roll 3 'lots-o-sugar' $2.50 'image location'

还有更多数据,但我认为您在表格中明白了。

我的菜单看起来像这样:(HTML 页面)茶、沙拉和糕点将是单击时仅显示其项目的链接。下面是一个粗略的例子,假设沙拉是当前页面。

**Bar**           'Caesar image', Caesar, hail Caesar, $5.00
Teas 'Greek image', Greek, Plato's fav, $3.00
**Kitchen**
Salads
Pastries

目前,我在一个类中构建了这一切。一个对象。我最终构建了三个阵列

$this->types      = array(
[0] => array(
'id' => 1,
'name' => 'Bar'
),
[1] => array(
'id' => 2,
'name' => 'Kitchen'
)
);

$this->categories = array(
[Bar] => array(
'id' => 2,
'name' => 'Teas',
'type_id' => 1
)
),
[Kitchen] => array(
'id' => 1,
'name' => 'Salads',
'type_id' => 2
),
array(
'id' => 3,
'name' => 'Patries',
'type_id' => 2
)
);

$this->items 有自己的数组,$this->category[id] 作为主键。

虽然这一切都变得非常困惑。尝试针对菜单的不同部分遍历这些数组是很糟糕的。我没有包括代码,因为我觉得整个思考过程从根本上是错误的。我不是在找人给我一个完整的代码示例,只是帮助我思考过程。我认为这是编码中最难的部分,即思考问题的解决方案。

总而言之,我希望创建一个动态菜单,该菜单既可以根据类别过滤项目,也可以根据类型过滤项目

为了好玩,这是我使用的代码:

菜单.php

    <?php

class menu{

private $category;
private $size;
private $types;
private $categories;
private $items = array();

public function __construct(){
$this->setTypes();
$this->setCategories();
$this->setItems();
}

private function setTypes(){
$sql = "SELECT * FROM bbc_menu_types";
$this->types = db::rowAsAssocArray($sql);
}

public function getTypes(){
return $this->types;
}

private function setCategories(){

for ($i = 0; $i < count($this->types); $i++){
$typeId = $this->types[$i]['id'];
$sql = "SELECT * FROM bbc_menu_categories WHERE type_id = $typeId";
$this->categories[$this->types[$i]['name']] = db::rowAsAssocArray($sql);
}
}

public function getCategories(){
return $this->categories;
}

public function setItems(){
foreach ($this->categories as $key => $value){
for ($i = 0; $i < count($value); $i++){
$catId = $value[$i]['id'] . '<br />';
settype($catId, 'integer');
$sql = "SELECT * FROM bbc_menu_items WHERE category_id = $catId";
$this->items[$this->categories[$key][$i]['name']] = db::rowAsAssocArray($sql);
}
}
}

public function getItems(){
return $this->items;
}
}


?>

db.pgp(摘录)

public static function rowAsAssocArray($sql){
try{
//do not touch
$data=null;
$stmt = self::$link->prepare($sql);
$stmt->execute();
while ($result = $stmt->fetchAll(PDO::FETCH_ASSOC)){
foreach ($result as $key => $value){
$data[] = $value;
}
}
return $data;
}
catch (PDOException $e){
print $e->getMessage();
}
}

html(专家)

<?php
$i=0;
foreach ($types as $value){
echo "<li><h3>" . $types[$i]['name'] . "</h3></li>";
$i2 = 0;
while ($i2 <count($categories[$types[$i]['name']])){
if ($_GET['cat'] === strtolower($categories[$types[$i]['name']][$i2]['name'])){
echo "<li class='active'><a href='?rt=menu&amp;cat=";
} else {
echo "<li><a href='?rt=menu&amp;cat=";
}
echo strtolower($categories[$types[$i]['name']][$i2]['name']) . "'>" . $categories[$types[$i]['name']][$i2]['name'] . "</a></li>";
$i2++;
}
$i++;
}
?>
</ul>
</nav>
</div><!-- end menu-links -->
</div><!-- end col -->

<div class="col-sm-12 col-md-9">
<div class="menu-links-big">
<?php
$i = 0;
while ($i < count($items[ucfirst($_GET['cat'])])){
?>
<div class="menu-item">
<img src="<?php echo $items[ucfirst($_GET['cat'])][$i]['image']; ?>" alt="" class="img-thumbnail shadow alignleft">
<h3><?php echo $items[ucfirst($_GET['cat'])][$i]['name']; ?></h3>
<p><?php echo $items[ucfirst($_GET['cat'])][$i]['description']; ?></p>
<div class="price"><?php echo '$' . $items[ucfirst($_GET['cat'])][$i]['price']; ?></div>
</div><!-- end item -->
<?php
$i++;
}
?>

就像我说的......一团糟......显然可以进行清洁。除此之外还有清理和重构。我意识到。在我决定询问之前,我刚刚完成工作。

最佳答案

我觉得这样一个结构良好的问题应该得到更长的答案。

对于这种情况,我强烈建议使用 Doctrine .

然后您可以简单地编写您的 3 个实体,例如:

类型.php

<?php
// src/Type.php

use Doctrine\Common\Collections\ArrayCollection;

/** @Entity */
class Type
{
/**
* @Id
* @Column(type="integer")
* @GeneratedValue
**/
protected $id;

/** @Column(type="string") **/
protected $name;

/** @OneToMany(targetEntity="Category", mappedBy="type") **/
protected $categories;

public function __construct()
{
$this->categories = new ArrayCollection();
}

public function getId()
{
return $this->id;
}

public function getName()
{
return $this->name;
}

public function setName($name)
{
$this->name = $name;

return $this;
}

public function addCategory($category)
{
$category->setType($this);
$this->categories->add($category);

return $this;
}

public function removeCategory($category)
{
$category->setType(null);
$this->categories->remove($category);

return $this;
}

public function getCategories()
{
return $this->categories;
}
}

分类.php

<?php
// src/Category.php

use Doctrine\Common\Collections\ArrayCollection;

/** @Entity */
class Category
{
/**
* @Id
* @Column(type="integer")
* @GeneratedValue
**/
protected $id;

/** @Column(type="string") **/
protected $name;

/**
* @ManyToOne(targetEntity="Type", inversedBy="categories")
* @JoinColumn(name="type_id", referencedColumnName="id")
*/
protected $type;

/** @OneToMany(targetEntity="Item", mappedBy="category") **/
protected $items;

public function __construct()
{
$this->items = new ArrayCollection();
}

public function getId()
{
return $this->id;
}

public function getName()
{
return $this->name;
}

public function setName($name)
{
$this->name = $name;

return $this;
}

public function getType()
{
return $this->type;
}

public function setType($type)
{
$this->type = $type;
}

public function addItem($item)
{
$item->setCategory($this);
$this->items->add($item);

return $this;
}

public function removeItem($item)
{
$item->setCategory(null);
$this->items->remove($item);

return $this;
}

public function getItems()
{
return $this->items;
}
}

项目.php

<?php
// src/Item.php

use Doctrine\Common\Collections\ArrayCollection;

/** @Entity */
class Item
{
/**
* @Id
* @Column(type="integer")
* @GeneratedValue
**/
protected $id;

/** @Column(type="string") **/
protected $name;

/**
* @ManyToOne(targetEntity="Category", inversedBy="items")
* @JoinColumn(name="category_id", referencedColumnName="id")
*/
protected $category;

public function getId()
{
return $this->id;
}

public function getName()
{
return $this->name;
}

public function setName($name)
{
$this->name = $name;

return $this;
}

public function getCategory()
{
return $this->category;
}

public function setCategory($category)
{
$this->category = $category;

return $this;
}
}

设置完所有这些后,Doctrine 将生成您的表格,您可以像这样简单地查询您的信息:

$repo = $entityManager->getRepository("Type");
$kitchen = $repo->findOneBy(array("name" => "Kitchen"));

echo "Fetching 'Kitchen'-Categories...<br/>";
$categories = $kitchen->getCategories();
foreach($categories as $category)
{
$itemsInCategory = $category->getItems();

echo "Category: ".$category->getName().", Items:<br/>";
foreach($itemsInCategory as $item)
{
echo $item->getName()."<br/>";"
}
}

如您所见,此时只需调用 getter 来查询整个树即可。

这里有两个示例文件来向您展示用法:

创建/存储对象:

<?php
// createTest.php
require_once "bootstrap.php";

// Create 'Bar' Type
$bar = new Type();
$bar->setName("Bar");
$entityManager->persist($bar);

// Create 'Kitchen' Type
$kitchen= new Type();
$kitchen->setName("Kitchen");
$entityManager->persist($kitchen);


// Create 'Salads' Category...
$salads = new Category();
$salads->setName("Salads");
$entityManager->persist($salads);

// ... and add it to the kitchen
$kitchen->addCategory($salads);

// Create Teas and add to Bar
$teas = new Category();
$teas->setName("Teas");
$entityManager->persist($teas);

$bar->addCategory($teas);

// Create Pastries and add to Kitchen
$pastries = new Category();
$pastries->setName("Pastries");
$entityManager->persist($pastries);

$kitchen->addCategory($pastries);

// Add some Items
$caesar = new Item();
$caesar->setName("Caesar Salad");
$entityManager->persist($caesar);

$salads->addItem($caesar);


$entityManager->flush();

查询对象:

<?php
// queryTest.php
require_once "bootstrap.php";

$typeRepo = $entityManager->getRepository("Type");

$types = $typeRepo->findAll();

echo "Found ".count($types)." types:\n";
foreach($types as $type)
{
echo $type->getName()."\n";

foreach($type->getCategories() as $category)
{
echo " - ".$category->getName()."\n";

foreach($category->getItems() as $item)
{
echo " - ".$item->getName()."\n";
}
}
}

输出:

Found 2 types:
Bar
- Teas
Kitchen
- Salads
- Caesar Salad
- Pastries

此时您可以玩各种恶作剧,向您的类添加更多属性/方法只是声明它们、提供可靠的原则注释和更新数据库的问题。

额外的好处是您独立于数据库,该示例使用 sqlite,因为它易于设置,但您也可以使用 mysql 或任何其他 PDO 支持的数据库。 Doctrine 还关注 SQL 注入(inject),因为它使用准备好的语句。

有关更详细的示例,请查看顶部链接的文档!

关于php - 我应该使用数组还是对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34637660/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com