下面由Laravel教程栏目给大家介绍个人推荐的 laravel 或其它框架的编程规范,希望对需要的朋友有所帮助!
在开发的时候,许多同学在文件命名方面,容易出现絮乱,随意性强,没有统一性。此种情况,在多人协同时,尤为突出。各开发人员都要去适应每个人的开发习惯,诸多不便,阻碍了多人协同开发的效率。
使用统一的开发规范,好处甚多。减少开发间的磨合,是其一,举例:
app/Models/User.php
···/**
* @desc 获取 users.username
* @param int $user_id users.id
* @return string
*/public static function getUsername(int $user_id): string{
return self::where('id', $user_id)->value('username');}// getUsername() end/**
* @desc 获取 users.age
* @param int $user_id users.id
* @return int
*/public static function getAge(int $user_id): int{
return (int)self::where('id', $user_id)->value('age');}// getAge() end···在行参 $user_id 的注释里,我使用的是 users.id 的形式。此形式是我主推的,优点是直观的知道此参数的由来(users 表中 id 字段)。
返回的参数也做了直观的说明,取值为 users 表中 username 字段的值。function 命名按照动作来区分命名,get + 字段 取值,set + 字段 更新值。
下面,我通过 users 表举例,列举我推荐命名的逻辑。
以 users 表来作为蓝本,向同学们推行此规范。
database/migrations/xxxx_create_users_table.php
···use Illuminate\Support\Facades\DB;··· Schema::create('balance_logs', function (Blueprint $table) {
$table->id();
$table->string('username', 32)->unique()->nullable(false)->comment('名称');
$table->string('password', 128)->nullable(false)->comment('密码');
$table->unsignedInteger('age', 3)->default(0)->comment('年龄');
$table->string('token', 128)->nullable(true)->comment('登录态');
$table->dateTime('created_at')->useCurrent();
$table->dateTime('updated_at')->useCurrent();
$table->index('username', 'username_index');
});
DB::statement("ALTER TABLE `users` comment '用户表'");···app/Models/User.php
app/Http/Controllers/UserController.php
<?phpnamespace App\Http\Controllers\Api\v1;use App\Http\Controllers\Controller;use Illuminate\Http\Request;use App\Models\User;class UserController extends Controller{
public function index(Request $request)
{
// todo
}// index() end
public function show(Request $request)
{
// 变量命名,对应的是表字段的话,变量名建议以该字段为名,
// 注释时采用 表名.字段 的形式
// users.username
$username = $request->post('username');
}// show() end
public function store(Request $request)
{
$user_id = $request->post('user_id');// users.id
$age = $request->post('age'); // users.age
// 更新数据
User::where('id', $user_id)->update(['age' => $age]);
}// store() end}app/Http/Requests/UserRequest.php
app/Observers/UserObserver.php
app/Console/Commands/UserCommand.php
$ php artisan my:user
我将上面此种规范定义为 以表规名,对此的解释是,以表名为主线,规定其相关业务的文件,均以表名为关键字进行后续文件的命名。

希望我的个人建议,能在同学们间推行与流行起来。谢谢同学们的阅读,记得帮我 点赞、评论、收藏、转发。
以上就是分享个人推荐的laravel或其它框架的编程规范的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号