gpt4 book ai didi

php - laravel 5.1 中的安全和干净代码

转载 作者:可可西里 更新时间:2023-10-31 22:10:24 25 4
gpt4 key购买 nike

其实我有一个关于代码清理的问题
我试图在 blade file 中获得一些值(value),我对两种方法感到困惑我认为两者都是正确的,但我需要知道谁的原因更干净、更安全

在我的 Blade 中直接使用 Eloquent 的第一种方法

@foreach
(Auth::user()->company->country->cities as $city) {{$city->name}}
@endforeach

第二种使用注入(inject)服务的方法是在我的模型中创建此方法并使用 laravel 5.1 注入(inject)服务在我的 Blade 中使用它

public function getCity()
{
foreach(Auth::user()->company->country->cities as $city) {
return $city->name ;
// OR
return $city ;
// i think this is one of benefits to use this approach
// because in my view i can use getCity()->id or getCity()->name
}
}

感谢您的宝贵时间。

最佳答案

第二种方法行不通,因为该函数将在返回第一个城市(或第一个城市本身)的名称时完成。要使其工作,您可以重写它,以便它返回所有城市并在 blade 中循环遍历它们。

因此,如果您使用该函数,您的代码可能如下所示:

@foreach($serviceName->getCities() as $city)
{{ $city->name }}
@endforeach

这是一件好事,因为 View 不必关心城市的来源。如果您在不同的 View 上使用这样的服务,更新起来会容易得多。

关于安全性:这两种方法之间没有区别。只要您使用“{{ }}”运算符打印输出。它会阻止可能的 XSS攻击。

关于php - laravel 5.1 中的安全和干净代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33460586/

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