我是Java转的php,这两天开始学习php,但是因为赶进度学的很快,3天功夫就开始搭建Laravel框架了,只是说是知其然而不知其所以然,相当于从零开始,写的学习Laraveldemo的源码在我的github akaedison/blog (github.com) 上,大家刚开始学的话可以参照一下。
一.Laravel的安装与配置
1.下载Composer-Setup.exe (getcomposer.org)并安装
2.移动到xampp/hotdocs文件夹,执行以下命令
php composer create-project --prefer-dist laravel/laravel blog
3.用PhpStorm打开可以看到如图项目结构
4.可以直接输入命令 php artisan serve 运行,也可以访问apache,显示如下图表示成功
这时Laravel就安装成功了。
5.修改.env文件中的数据库信息
二.编写api接口
1.新建数据库建表插入数据
DROP TABLE IF EXISTS `book`;
CREATE TABLE `book` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`book_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
`book_sort` int(11) DEFAULT NULL,
`book_mark` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = MyISAM AUTO_INCREMENT = 5 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of book
-- ----------------------------
INSERT INTO `book` VALUES (1, '水浒传', 1, '四大名著');
INSERT INTO `book` VALUES (2, '西游记', 1, '孙悟空');
INSERT INTO `book` VALUES (3, '红楼梦', 2, '无');
INSERT INTO `book` VALUES (4, '三国演义', 2, '');
3.新建Model和Controller
php artisan make:model Models/Book
php artisan make:controller BookController
修改Book.php
<?php
namespace AppModelsModels;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
class Book extends Model
{
use HasFactory;
/**关联到模型的数据表
* @var string
*/ protected $table = 'book';
/**Laravel有默认时间字段,不需要可以修改成 false
* @var bool
*/ public $timestamps = false;
}
4.创建简单的api
编写BookController.php
<?php
namespace AppHttpControllers;
use AppModelsModelsBook;
use IlluminateHttpRequest;
class BookController extends Controller
{
public function getBookById($id)
{ // 根据id查询
$book = Book::find($id);
// return response()是返回想要 json()转换成json字符串但是是unicode setEncodingOptions设置编码
return response()->json($book)->setEncodingOptions(JSON_UNESCAPED_UNICODE);
}
}
编写 routes/api.php
<?php
use IlluminateHttpRequest;
use IlluminateSupportFacadesRoute;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::any('/book/{id}',[AppHttpControllersBookController::class,'getBookById']);
5.php artisan serve或者直接访问apache
一个简单接口的编写到此结束,这样写起来很简单,但是中间也遇到了点小问题,比如MySQL编码问题,Navcat有很大的问题,show variables like 'char%';在MySQL cmd中显示是utf-8但是在navcat中却成了latin,这个要在navcat连接那里编辑编码为自动,这样就可以和系统的一样了。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。