laravel怎么laravel 自动加载类Model和一些常用的类

Laravel5.1 启动详解 - 林锅 - 博客园
随笔 - 210, 文章 - 0, 评论 - 5, 引用 - 0
Laravel所有请求的入口文件是:/public/index.php,代码如下
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
| Composer provides a convenient, automatically generated class loader for
| our application. We just need to utilize it! We'll simply require it
| into the script here so that we don't have to worry about manual
| loading any of our classes later on. It feels nice to relax.
//自动加载文件设置
require __DIR__.'/../bootstrap/autoload.php';
|--------------------------------------------------------------------------
| Turn On The Lights
|--------------------------------------------------------------------------
| We need to illuminate PHP development, so let us turn on the lights.
| This bootstraps the framework and gets it ready for use, then it
| will load up this application so that we can run it and send
| the responses back to the browser and delight our users.
//初始化服务容器,即框架的 IoC 容器,生成一个Laravel应用实例
$app = require_once __DIR__.'/../bootstrap/app.php';
|--------------------------------------------------------------------------
| Run The Application
|--------------------------------------------------------------------------
| Once we have the application, we can handle the incoming request
| through the kernel, and send the associated response back to
| the client's browser allowing them to enjoy the creative
| and wonderful application we have prepared for them.
//通过服务容器生成一个 HTTP / Console kernel类的实例
$kernel = $app-&make(Illuminate\Contracts\Http\Kernel::class);
//kernel类实例运行handle方法,接收请求和处理结果(主要是运行middleware和URL相关的controller)
$response = $kernel-&handle(
$request = Illuminate\Http\Request::capture()
//返回处理结果
$response-&send();
//为整个请求处理周期展示最后的任何想要提供的动作,如每次访问后想要记录用户行为、给前端发消息
$kernel-&terminate($request, $response);
(1)自动加载文件
  自动加载文件功能是通过Composer实现的,在composer.json中设置的加载方式里提取加载路径,然后根据Laravel对应的加载方式进行处理,主要为四种加载方式:
PSR0加载方式&对应的文件就是autoload_namespaces.php
PSR4加载方式&对应的文件就是autoload_psr4.php
其他加载类的方式&对应的文件就是autoload_classmap.php
加载公用方法&对应的文件就是autoload_files.php
  具体的定义形式在 composer.json 里面设置路径,如下:
"autoload": {
"classmap": [
"database"
"psr-4": {
"App\\": "app/",
"App\\Http\\Models\\": "app/Http/Models/"
"autoload-dev": {
"classmap": [
"tests/TestCase.php"
(2)初始化服务容器
  The Laravel service container is a powerful tool for managing class dependencies and performing dependency injection.
  这句话是指 Laravel 服务容器的核心是依赖注入(也是控制反转,一种设计模式),它是把在类里面定义实例的这种高耦合模式摒弃掉,虽然工厂模式也行,不过也比较不灵活,然后以一种依赖的方式去把相关的类注册在容器里,需要时再把类实例从容器提取出来注入到本身。
  本质上是分离,将各种功能分离开,保证了松耦合,例如应用程序用到Foo类,Foo类需要Bar类,Bar类需要Bim类,那么先创建Bim类,再创建Bar类并把Bim注入,再创建Foo类,并把Bar类注入,再调用Foo方法,Foo调用Bar方法,接着做些其它工作。
  Laravel这个过程粗略的有以下几个步骤:
  1、registerBaseBindings:初始化基本的容器实例。
  2、registerBaseServiceProviders:注册基本的service provider,有两个:event、route。event service provider会设置队列的处理工厂,route service provider定义一些路由行为,包括请求、反应、重定向这些。
  3、registerCoreContainerAliases:注册核心的容器功能类的别名,这些类包括验证、缓存、配置、队列、session等。
(3)生成kernel类
  The HTTP kernel extends the Illuminate\Foundation\Http\Kernel class, which defines an array of bootstrappers that will be run before the request is executed. These bootstrappers configure error handling, configure logging, detect the application environment, and perform other tasks that need to be done before the request is actually handled.
  The HTTP kernel also defines a list of HTTP middleware that all requests must pass through before being handled by the application. These middleware handle reading and writing the HTTP session, determine if the application is in maintenance mode, verifying the CSRF token, and more.
(4)kernel handle处理
  将kernel当成黑盒来看,接收请求、处理请求。Laravel数据库操作的三种方式 - CSDN博客
Laravel数据库操作的三种方式
本篇博客需要你有laravel的基础,laravel入门传送门 :
Laravel提供了3种操作数据库方式:DB facade(原始方式)、查询构造器和Eloquent ORM。
数据库的配置文件在config目录下的database.php里。打开这个文件,找到mysql的配置项。
这里有个env,它其实是调用了laravel根目录下的.env文件,这个文件存储了数据库的配置信息。打开它。修改为项目的数据库信息即可。
请自行建一个数据库,其中数据库得包含vipinfo表,并且插入一些数据,以方便下面使用。表的结构如下图。
顾名思义:这张表是会员表,分别有会员ID(主键),会员名字,会员类型,会员积分等字段。
一、数据库操作之DB facade
& &在app-&Http-&Controllers目录下新建一个Student控制器,StudentController.php。&StudentController.php代码如下:
namespace App\Http\C
use Illuminate\Support\Facades\DB;
class StudentController extends Controller {
}& 1.查询操作
& 在Student控制器里添加一个test1方法,查询用的是DB类的静态方法select(),参数是原生的sql语句,返回的是一个二维数组。dd()是laravel提供的方法,可以将一个数组以节点树的形式展示出来。具体代码如下:
public function test1()
$student=DB::select(&select * from vipinfo&);
//返回一个二维数组
var_dump($student);
//以节点树的形式输出结果
dd($student);
&路由配置:&Route::get('test1',['uses'=&'StudentController@test1']); &&
还不知怎样配置路由的,可以参考我之前的博客:
&URL访问:http://localhost/laravel/public/index.php/test1 ,则会打印出结果。
&2.新增操作
新增使用的是DB类的静态方法insert(),第一个参数是sql语句,第二个参数是一个数组,数组里放要插入的数据。这里?是占位符,通过数据库接口层pdo的方式,达到防sql注入的目的。返回的是执行的结果。插入成功则返回true,否则为false。
$bool=DB::insert(&insert into vipinfo(vip_ID,vip_name,vip_type,vip_fenshu)
values(?,?,?,?)&,[5,'小明','出行',670]);
var_dump($bool);
//新增成功则返回true。3. 更新操作
更新使用的是DB类的静态方法update(),第一个参数是sql语句,第二个参数是一个数组,数组里的元素分别对应sql语句里的问号。更新成功返回true。
$bool=DB::update('update vipinfo set vip_fenshu= ? where vip_ID= ? ',[700,5]);
var_dump($bool);
//更新成功返回true4. 删除操作
删除使用的是DB类的静态方法delete(),第一个参数是sql语句,第二个参数是一个数组,数组里的元素分别对应sql语句里的问号。返回的是删除的行数。
$num=DB::delete('delete from vipinfo where vip_ID= ?',[5]);
二、数据库操作之查询构造器
laravel查询构造器提供了方便流畅的接口,用来建立及执行数据库查找语法。使用了pdo参数绑定,使应用程序免于sql注入,因此传入的参数不需要额外转义特殊字符。基本上可以满足所有的数据库操作,而且在所有支持的数据库系统上都可以执行。
1.使用查询构造器实现增删改查
同样在Student控制器里测试以下代码:
$bool=DB::table(&vipinfo&)-&insert(['vip_ID'=&6,'vip_name'=&'zls','vip_type'=&&出行&,'vip_fenshu'=&800]);
//返回bool值
//如果想得到新增的id,则使用insertGetId方法
$id=DB::table(&vipinfo&)-&insertGetId(['vip_ID'=&5,'vip_name'=&'wyp','vip_type'=&&出行&,'vip_fenshu'=&800]);
//插入多条数据
$bool=DB::table(&vipinfo&)-&insert([
['vip_ID'=&5,'vip_name'=&'wyp','vip_type'=&&出行&,'vip_fenshu'=&800],
['vip_ID'=&6,'vip_name'=&'zls','vip_type'=&&出行&,'vip_fenshu'=&800],
//返回bool值
$bool=DB::table(&vipinfo&)-&where('vip_ID',6)-&update(['vip_fenshu'=&500]);
$bool=DB::table(&vipinfo&)-&where('vip_ID',6)-&increment(&vip_fenshu&);//自增1
$bool=DB::table(&vipinfo&)-&where('vip_ID',6)-&increment(&vip_fenshu&,3);//自增3
$bool=DB::table(&vipinfo&)-&where('vip_ID',6)-&decrement(&vip_fenshu&);//自1
$bool=DB::table(&vipinfo&)-&where('vip_ID',6)-&decrement(&vip_fenshu&,3);//自增3
//自增时再修改其他字段
$bool=DB::table(&vipinfo&)-&where('vip_ID',6)-&increment(&vip_fenshu&,3,['vip_name'=&'dbdibi']);//自增3
$num=DB::table(&vipinfo&)-&where('vip_ID',6)-&delete();//删除1条
$num=DB::table(&vipinfo&)-&where('vip_ID','&',4)-&delete();//删除多条
//删除的行数
$num=DB::table(&vipinfo&)-&truncate();//删除整表,不能恢复,谨慎使用
//get()返回多条数据
$student=DB::table(&vipinfo&)-&get();
var_dump($student);
//first()返回1条数据
$student=DB::table(&vipinfo&)-&first();
//结果集第一条记录
$student=DB::table(&vipinfo&)-&orderBy('vip_ID','desc')-&first();//按vip_ID倒序排序
var_dump($student);
//where()条件查询
$student=DB::table(&vipinfo&)-&where('vip_ID','&=',2)-&get(); //一个条件
$student=DB::table(&vipinfo&)-&whereRaw('vip_ID& ? and vip_fenshu &= ?',[2,300])-&get(); //多个条件
dd($student);
//pluck()指定字段,后面不加get
$student=DB::table(&vipinfo&)-&pluck('vip_name');
dd($student);
//lists()指定字段,可以指定某个字段作为下标
$student=DB::table(&vipinfo&)-&lists('vip_name','vip_ID');
//指定vip_ID为下标
dd($student);
$student=DB::table(&vipinfo&)-&lists('vip_name');
//不指定下标,默认下标从0开始
//select()指定某个字段
$student=DB::table(&vipinfo&)-&select('vip_name','vip_ID')-&get();
dd($student);
//chunk()每次查n条
$student=DB::table(&vipinfo&)-&chunk(2,function($students){
//每次查2条
var_dump($students);
if(.......)
//在满足某个条件下使用return就不会再往下查了
2.使用聚合函数
//count()统计记录条数
$nums=DB::table(&vipinfo&)-&count();
//max()某个字段的最大值,同理min是最小值
$max=DB::table(&vipinfo&)-&max(&vip_fenshu&);
//avg()某个字段的平均值
$avg=DB::table(&vipinfo&)-&avg(&vip_fenshu&);
//sum()某个字段的和
$sum=DB::table(&vipinfo&)-&sum(&vip_fenshu&);
四、数据库操作之 - Eloquent ORM&
1.简介、模型的建立及查询数据
简介:laravel所自带的Eloquent ORM&是一个ActiveRecord实现,用于数据库操作。每个数据表都有一个与之对应的模型,用于数据表交互。
建立模型,在app目录下建立一个Student模型,即Student.php,不需要带任何后缀。
namespace A
use Illuminate\Database\Eloquent\M
class Student extends Model{
//指定表名
protected $table= 'vipinfo';
//指定主键
protected $primaryKey= 'vip_ID';
在Student控制器里增加一个test3方法,配置路由Route::get('test3',['uses'=&'StudentController@test3']);
public function test3(){
// all()方法查询所有数据
$studnets=Student::all();
dd($studnets);
//find()查询一条,依据主键查询。findOrFail()查找不存在的记录时会抛出异常
$student=Student::find(5);
//主键为5的记录
var_dump($student['attributes']);
//查询构造器的使用,省略了指定表名
$student=Student::get();
var_dump($student);
2 . 新增数据、自定义时间戳、批量赋值
(1)使用save方法新增
laravel会默认维护created_at,updated_at 两个字段,这两个字段都是存储时间戳,整型11位的,因此使用时需要在数据库添加这两个字段。如果不需要这个功能,只需要在模型里加一个属性:public $timestamps= 以及一个方法,可以将当前时间戳存到数据库
protected function getDateFormat(){
return time();
这样就不需要那两个字段了。
控制器里写:
$student=new Student();
//设定数据
$student-&vip_name='xiaoming';
$student-&vip_type='出行';
$student-&vip_fenshu=900;
$bool=$student-&save();
从数据库里取得某条记录的时间戳时,默认取得的是按日期格式化好的时间戳,如果想取得原本的时间戳,则在模型里增加asDateTime方法。
protected function asDateTime($val){
(2)使用create方法新增时,需要在模型里增加:
protected $fillable=['vip_name','vip_fenshu','vip_type'];
//允许批量赋值的字段
&控制器里写:
Student::create(['vip_name'=&'mmm','vip_fenshu'=&999,'vip_type'=&'出行']);这样即可新增成功!
(3)firstOrCreate()以属性查找记录,若没有则新增
$student=Student::firstOrCreate(['vip_name'=&'mmm']);
(4)firstOrNew()以属性查找记录,若没有则会创建新的实例。若需要保存,则自己调用save方法()
$student=Student::firstOrNew(['vip_name'=&'mmm']);
$student-&save();
3. &修改数据
//通过模型更新数据
$student=Student::find(2);
$student-&vip_fenshu=10000;
$student-&save(); //返回bool值
//通过查询构造器更新
$num=Student::where('vip_ID','&',2)-&update(['vip_fenshu'=&2000]);
//返回更新的行数
4. &删除数据
//(1)通过模型删除数据
$student=Student::find(11);
$student-&delete(); //返回bool值
//(2)通过主键删除
$num=Student::destroy(10); //删除主键为10的一条记录
echo $ //返回删除的行数
$num=Student::destroy(10,5); //删除多条
或者$num=Student::destroy([10,5]);
echo $ //返回删除的行数
更多laravel系列的教程可参考我的laravel文章分类~~
视频资源学习参考:
推荐一个基于Vue全家桶+Socket.io+Express/Koa2打造的网页版手机QQ,高仿腾讯QQ最新版本。
项目地址:
本文已收录于以下专栏:
相关文章推荐
数据库增删改查CURD操作// 添加数据
返回bool值
// $bool = DB::insert('insert into student(name,age) values(?,?)',['im...
1、准备工作
1.1、下载好laravel5.1
1.2、创建数据库及表
-- 数据库: `myblog`
-- ------------------------------------...
查询构建器(Query Builder)
1、新增数据
使用查询构建器的insert方法即可插入一条/多条数据:
DB::table('users')-&insert([
    ['...
用户认证1. 自带用户认证简介
Laravel 让实现认证机制变得非常简单。事实上,几乎所有的设置默认就已经完成了。有关认证的配置文件都放在 config/auth.php 里,而在这些文件里也都...
Blade是Laravel提供的一个既简单又强大的模板引擎,Blade允许在视图中使用原生php代码,所有Blade视图页面都将被编译成原生php代码并缓存起来,除非你的模板文件被修改了,否则不会重新...
/* * 多个线程访问同一个数据  * 设计4个线程,其中俩个线程对j ++,俩个线程对j -- */package cn.itcast.heima.public class...
本篇博客需要你有laravel的基础,laravel入门传送门 :http://blog.csdn.net/zls/article/details/
数据库操作之-Eloquent ORM
Eloquent ORM简介、模型的建立及查询数据
Eloquent ORM中新增数据、自定义时间戳及批量赋值的使用
使用Eloquent ORM修改数据
一、laravel简介及安装
1.简介:Laravel是一套简洁、优雅的PHP Web开发框架(PHP Web Framework)。它可以让你从面条一样杂乱的代码中解脱出来;它可以帮你构建一个完美的...
最近项目里需要处理跨域请求,遇到了一些问题,中间走了很多坑,深挖了很多细节,受益良多。
cors在跨域解决方案中算是很好用的,网上资料一大堆,只需要在服务器端进行配置即可。
配置方法网上也很多,我简单...
他的最新文章
讲师:吴岸城
您举报文章:
举报原因:
原文地址:
原因补充:
(最多只允许输入30个字)在 SegmentFault,解决技术问题
每个月,我们帮助 1000 万的开发者解决各种各样的技术问题。并助力他们在技术能力、职业生涯、影响力上获得提升。
一线的工程师、著名开源项目的作者们,都在这里:
获取验证码
已有账号?
问题对人有帮助,内容完整,我也想知道答案
问题没有实际价值,缺少关键内容,没有改进余地
1、在 app\Libraires 下定义一个类 QrCode.php
* Created by PhpStorm.
* User: AIMPER
* Time: 10:13
namespace App\L
use Endroid\QrC
use Illuminate\Support\Facades\DB;
class QrCode{
public static function generateQrCode($type = null, $id = null){
$code = random_string(32,true);
$create_date = time();
$expires = 0;
$qrcodeType = DB::table('qrcode_type')-&where('id','=',$type)-&select('code','params')-first();
return $qrcodeT
2、调用该类的方法
use App\Libaries\QrC
class TestController extends Controller{
public function index(){
QrCode::generateQrCode(11,1);
3、报错信息
ReflectionException in Route.php line 286:
Class App\Libaries\QrCode does not exist
4、解决尝试有使用 composer dump-autoload 过,但是类还是没法加载进来,请问如何把自定义的类自动加载到项目中?
答案对人有帮助,有参考价值
答案没帮助,是错误的答案,答非所问
在路由中通过依赖注入获取的类,需要注册至容器。
分享到微博?
关闭理由:
删除理由:
忽略理由:
推广(招聘、广告、SEO 等)方面的内容
与已有问题重复(请编辑该提问指向已有相同问题)
答非所问,不符合答题要求
宜作评论而非答案
带有人身攻击、辱骂、仇恨等违反条款的内容
无法获得确切结果的问题
非开发直接相关的问题
非技术提问的讨论型问题
其他原因(请补充说明)
我要该,理由是:

我要回帖

更多关于 laravel config 加载 的文章

 

随机推荐