[英]Add function to controller in laravel 7
This might not be best practice- however my functions will be rather comprehensive and used by additional controllers, thus I would like to separate them from the controller's public class.这可能不是最佳实践 - 但是我的功能将相当全面并被其他控制器使用,因此我想将它们与控制器的公共 class 分开。 (what is best practice? I just want to load the functions to specific pages/controllers.) (最佳实践是什么?我只想将功能加载到特定页面/控制器。)
Laravel 7 Laravel 7
class HomeController extends Controller
{
function add($a, $b) {
print($a + $b);
}
public function show($id) {
add(1,2)
}
}
You shouldn't perform logic in the controller.您不应该在 controller 中执行逻辑。
I recommend you to create a Calculator
folder for example where you store the sum, something like this:我建议您创建一个Calculator
文件夹,例如存储总和的位置,如下所示:
The controller: controller:
declare(strict_types=1);
namespace App\Controller;
use App\Calculator;
final class HomeController extends Controller
{
// $id not needed, although, if you are going to use it,
// try to declare the type!
public function show() {
return (new Calculator())->add(1, 2);
}
}
And the calculation class:以及计算 class:
declare(strict_types=1);
namespace App\Calculator;
final class Calculator
{
public function add(float $firstOp, float $secondOp): float
{
return $firstOp + $secondOp;
}
}
PS : Do not print in the controller, you have to follow the SRP (Single Responsibility Principle): :) You can replace the return (new Calculator())->add(1, 2);
PS : 不要在 controller 中打印,你必须遵循 SRP (Single Responsibility Principle): :) 你可以替换return (new Calculator())->add(1, 2);
in the show()
method by a dd(new Calculator())->add(1, 2));
在show()
方法中由dd(new Calculator())->add(1, 2));
for example.例如。
Seems like a solution for using a trait a common practice in Laravel.似乎是使用特征的解决方案,这是 Laravel 中的常见做法。
namespace App\Http\Controllers;
use App\Traits\MySpecialFunctions;
class HomeController extends Controller
{
use MySpecialFunctions;
}
namespace App\Traits;
trait MySpecialFunctions {
function add($a, $b) {
print($a + $b);
}
public function show($id) {
add(1,2)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.