内置表 sqlite_使用PHP的内置服务器和SQLite在Laravel中快速进行原型制作

内置表 sqlite

If you are a seasoned Laravel developer, you know the usual project setup drill that involves creating a new project, a fresh database, and adding a virtual host entry to Apache.

如果您是经验丰富的Laravel开发人员,您将了解通常的项目设置演练,其中涉及创建一个新项目,一个新数据库以及向Apache添加虚拟主机条目。

If you are starting from scratch, the Apache and MySQL installation can take some time and slow things down for you.

如果您是从头开始的,那么Apache和MySQL的安装可能会花费一些时间并使您的工作变慢。

However, I will show you how you can jump start your Laravel development without Apache and MySQL.

但是,我将向您展示在没有Apache和MySQL的情况下如何快速启动Laravel开发。

During the course of this article, you will learn how to:

在本文的过程中,您将学习如何:

  1. Use the PHP server by itself.

    单独使用PHP服务器。
  2. Run your Laravel application with the PHP server.

    用PHP服务器运行Laravel应用程序。
  3. Integrate SQLite into your Laravel application.

    将SQLite集成到您的Laravel应用程序中。

PHP Web服务器 ( The PHP Web Server )

As of version 5.4.0, PHP provides a built-in webserver that can be used to run your PHP applications without setting up any webserver software. Under controlled environments, this works well for testing and demonstration but be advised, it is not intended to replace a fully functional web server.

从5.4.0版开始,PHP提供了内置的Web服务器,可用于运行PHP应用程序而无需设置任何Web服务器软件。 在受控环境下,此方法可很好地用于测试和演示,但建议您注意,它并不是要替换功能齐全的Web服务器。

If you are interested in the technical details, you can have a look at PHP's documentation

如果您对技术细节感兴趣,可以查看PHP的文档。

使用内置PHP服务器 ( Using the Built-in PHP Server )

Let's execute a simple PHP script to understand how this works.

让我们执行一个简单PHP脚本以了解其工作原理。

Fire up your code editor and create an index.php file.

启动您的代码编辑器并创建一个index.php文件。

<?php
phpinfo();
?>

In the terminal, move to the location where you just created your index.php file and summon the PHP server.

在终端中,移至您刚刚创建index.php文件的位置,并调用PHP服务器。

$cd /Volumes/Work/PHP/Server_Example/public_html
$ php -S localhost:8000
PHP 5.5.31 Development Server started at Wed Apr 20 20:46:29 2016
Listening on http://localhost:8000
Document root is /Volumes/Work/PHP/Server_Example/public_html
Press Ctrl-C to quit.

In your browser, navigate to http://localhost:8000 and you should see the ever famous, nicely formatted PHP's running configuration page.

在您的浏览器中,导航到http://localhost:8000 ,您应该看到曾经著名的,格式精美PHP的运行配置页面。

Let's throw in a little old-fashioned routing into the equation and see how things go.

让我们在方程式中加入一些老式的路由,看看情况如何。

Create another file named router.php

创建另一个名为router.php文件

switch ($_SERVER["REQUEST_URI"]) {
    case "/about":
        echo "<p style=\"text-align:center;\">This is the about page</p>";
        break;
    case "/portfolio":
        echo "<p style=\"text-align:center;\">This is the portfolio page</p>";
        break;
    case "/contact":
        echo "<p style=\"text-align:center;\">This is the contact page</p>";
        break;
    default:
        echo "<p style=\"text-align:center;\">This is the index page</p>";       
}

This script uses a simple switch statement to echo content based on the URL. You can navigate to these URLs by appending /about, /portfolio, and /contact to http://localhost:8000. Any URL that does not match will fire the default case and show the index page's content.

该脚本使用一个简单的switch语句根据URL回显内容。 您可以通过将/about/portfolio/contact附加到http://localhost:8000来导航到这些URL。 任何不匹配的URL都会触发默认大小写并显示索引页面的内容。

Execute the PHP server again but this time, also specify router.php as the routing file.

再次执行PHP服务器,但这一次,还要指定router.php作为路由文件。

$ php -S localhost:8000 router.php 
PHP 5.5.31 Development Server started at Wed Apr 20 21:55:52 2016
Listening on http://localhost:8000
Document root is /Volumes/Work/PHP/Server_Example/public_html
Press Ctrl-C to quit.

This exercise in routing shows you can do pretty much anything based on the URL that is requested by the client.

路由练习表明,您可以根据客户端请求的URL进行几乎所有操作。

Do frameworks employ this neat trick to fire the requested controller and action?

框架是否采用这种巧妙的技巧来触发请求的控制器和动作?

将服务器与Laravel一起使用 ( Using the Server with Laravel )

I wish professional software development was as simple as throwing a phpinfo page to the built in PHP server. Most of the time, you work with frameworks that have a number of files. You can easily get confused with which file to execute with the PHP server.

我希望专业的软件开发就像将phpinfo页面扔到内置PHP服务器一样简单。 大多数情况下,您使用的框架包含许多文件。 您可以很容易混淆使用PHP服务器执行哪个文件。

Do you simply run it at the root of your project and hope for the best?

您是否只是在项目的根部运行它并希望获得最好的结果?

Luckily, Laravel has Artisan's serve command that executes your application and spares you the headache.

幸运的是,Laravel具有Artisan的serve命令,该命令可以执行您的应用程序并serve您省力。

To run your Laravel application with the PHP server, simply execute the following command at the root of your project.

要在PHP服务器上运行Laravel应用程序,只需在项目的根目录执行以下命令。

$ php artisan serve
Laravel development server started on http://localhost:8000/

Artisan's serve command uses localhost, 8000, and development as the default host, port, and environment respectively. You can specify a different host, port, and environment using command line parameters.

Artisan的serve命令分别使用localhost8000development作为默认主机,端口和环境。 您可以使用命令行参数指定其他主机,端口和环境。

$ php artisan serve --host="www.scotch.io" --port=3000 --env="development"
Laravel development server started on http://www.scotch.io:3000/

In case you specify a host other than localhost, you should have it's entry in your /etc/hosts file.

如果您指定的主机不是localhost ,则应该在/etc/hosts文件中包含它的条目。

Here is how it should look like in case of the above host as a command line parameter.

这是上述主机作为命令行参数的情况下的外观。

##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting.  Do not change this entry.
##
127.0.0.1       localhost
255.255.255.255 broadcasthost
::1             localhost

# entry for command line host parameter
127.0.0.1       www.scotch.io

工匠的服务命令-深潜 ( Artisan's Serve Command - The Deep Dive )

Let's peek under the hood to figure out how the serve command works.

让我们来看看幕后如何serve命令的工作方式。

The serve command actually executes the server.php file which is at the root of your project.

serve命令实际上执行位于项目根目录的server.php文件。

<?php

/**
 * Laravel - A PHP Framework For Web Artisans
 *
 * @package  Laravel
 * @author   Taylor Otwell <taylorotwell@gmail.com>
 */

$uri = urldecode(
    parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)
);

//echo $uri;
//echo __DIR__.'/public'.$uri;

// This file allows us to emulate Apache's "mod_rewrite" functionality from the
// built-in PHP web server. This provides a convenient way to test a Laravel
// application without having installed a "real" web server software here.
if ($uri !== '/' && file_exists(__DIR__.'/public'.$uri)) {
    return false;
}

require_once __DIR__.'/public/index.php';

Other than simple URL parsing, the interesting bit is the if block. It simply makes sure that the url is not root / and a static asset has not been requested in which case it will simply serve the asset.

除了简单的URL解析之外,有趣的是if块。 它只是确保url不是root /并且没有请求静态资产,在这种情况下,它将仅为资产提供服务。

If the if conditional fails, the index.php file in the public directory is executed which simply creates the Laravel app, invokes a Kernel instance and passes it the request to handle.

如果if条件失败,将执行public目录中的index.php文件,该文件仅创建Laravel应用,调用Kernel实例并将请求传递给它处理。

<?php

/**
 * Laravel - A PHP Framework For Web Artisans
 *
 * @package  Laravel
 * @author   Taylor Otwell <taylorotwell@gmail.com>
 */

/*
|--------------------------------------------------------------------------
| 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.
|
*/

$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.
|
*/

$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);

$response = $kernel->handle(
    $request = Illuminate\Http\Request::capture()
);

$response->send();

$kernel->terminate($request, $response);

Notice the Request::capture() method, that is where all the magic to create the request happens.

注意Request::capture()方法,这就是创建请求的所有方法。

输入SQLite ( Enter SQLite )

Since it is nice to have the built-in PHP server to quickly spin an application, you would wonder if there also a way to skip the MySQL installation.

由于使用内置PHP服务器来快速旋转应用程序是一件很不错的事情,因此您想知道是否还有一种方法可以跳过MySQL安装。

Lucky for us, there is.

对我们来说很幸运。

If you are not familiar with SQLite, here is a short description from the official website.

如果您不熟悉SQLite,则这里是官方网站上的简短说明。

SQLite is an in-process library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine.

SQLite是一个进程内库,可实现自包含,无服务器,零配置的事务型SQL数据库引擎。

What this means is the database runs off from a single file on your storage. If you have the required libraries, you can communicate with the stored file just like you would normally talk to a database server.

这意味着数据库从存储中的单个文件运行。 如果您具有必需的库,则可以与存储的文件进行通信,就像通常与数据库服务器通信一样。

SQLite is an open source project so there are plugins available for popular languages such as PHP, Ruby, Python, and Java.

SQLite是一个开源项目,因此有一些插件可用于流行的语言,例如PHP,Ruby,Python和Java。

将SQLite与Laravel结合使用 ( Using SQLite with Laravel )

Laravel supports SQLite databases out of the box. With a little configuration, you can create applications that do not require a back-end database server.

Laravel开箱即用地支持SQLite数据库。 只需进行一些配置,就可以创建不需要后端数据库服务器的应用程序。

The first step in your configuration will be to create a SQLite database file named database.sqlite. I will create it inside the database directory which is at the root of your project. Ofcourse you can create your SQLite database anywhere but it is nice to keep things neat and in one place.

配置的第一步将是创建一个名为database.sqliteSQLite数据库文件。 我将在项目根目录的database目录中创建它。 当然,您可以在任何地方创建您SQLite数据库,但是最好将事情保持整洁并集中在一个地方。

Execute the following commands at the root of your project.

在项目的根目录执行以下命令。

$cd database
$ touch database.sqlite

The next step is to set the database related environment variables in the .env file at the root of your project.

下一步是在项目根目录的.env文件中设置与数据库相关的环境变量。

DB_CONNECTION=sqlite
DB_DATABASE=/Volumes/Work/PHP/Laravel-Sandbox/database/database.sqlite

The DB_CONNECTION and DB_DATABASE are the only variables required to configure SQLite for your project.

DB_CONNECTIONDB_DATABASE是为项目配置SQLite所需的唯一变量。

Though you have only set the DB_CONNECTION and DB_DATABASE variables, you will also notice a bunch of other database related variables such as DB_HOST and DB_PORT. You can ignore them for now as we will revisit them later to see how easy it is to switch back to MySQL.

尽管您仅设置了DB_CONNECTIONDB_DATABASE变量,但您还将注意到许多其他与数据库相关的变量,例如DB_HOSTDB_PORT 。 您现在可以忽略它们,因为稍后我们将再次访问它们,以了解切换回MySQL多么容易。

The final step is to set the configuration in the database configuration file.

最后一步是在数据库配置文件中设置配置。

Add the following sqlite key to the connections array in your config/database.php file.

将以下sqlite键添加到config/database.php文件中的connections数组。

'sqlite' => [
    'driver' => 'sqlite',
    'database' => env('DB_DATABASE', database_path('database.sqlite')),
    'prefix' => '',
],

Notice the database_path function which is a helper provided by Laravel to construct a path to a file which resides inside the database directory. It is used to specify a default path in case the environment variable DB_DATABASE is not set.

请注意, database_path函数是Laravel提供的帮助程序,用于构造驻留在database目录内的文件的路径。 如果未设置环境变量DB_DATABASE ,则用于指定默认路径。

Your application is ready to use SQLite as the backend database.

您的应用程序已准备好将SQLite用作后端数据库。

运行用户表迁移 ( Running the Users Table Migration )

As a test to make sure SQLite has been setup correctly, you are going to execute the users table migrations that are packaged with Laravel.

为了确保正确设置SQLite,请执行与Laravel一起打包的users表迁移。

In your terminal, execute the following commands.

在您的终端中,执行以下命令。

$ php artisan migrate:install --env=local
Migration table created successfully.

$ php artisan migrate --env=local
Migrated: 2014_10_12_000000_create_users_table
Migrated: 2014_10_12_100000_create_password_resets_table

All migrations were run successfully and the respective tables were created.

所有迁移均成功运行,并创建了相应的表。

Here's the look at all the tables in our SQLite table:

这是我们SQLite表中所有表的外观:

Laravel Artisan Migrate SQLite Table

Here are the migrations, password_resets and users tables:

以下是migrationspassword_resetsusers表:

Laravel Artisan Migrate Migrations Table
Laravel Artisan Migrate Users Table

Laravel Artisan迁移密码重置表

I am using Navicat for SQLite on OSX to view the contents of the SQLite database. You can download Navicat for your OS and follow the installation instructions. Once you are done with the installation, simply run Navicat and open the SQLite database file.

我在OSX上使用Navicat for SQLite来查看SQLite数据库的内容。 您可以为您的操作系统下载Navicat ,然后按照安装说明进行操作。 完成安装后,只需运行Navicat并打开SQLite数据库文件。

切换回MySQL ( Switching Back to MySQL )

If at any point during your project, you feel SQLite is not just cutting it out for you, you can switch to MySQL within a matter of seconds.

如果在项目进行中的任何时候,您都觉得SQLite不仅为您服务,那么您可以在几秒钟内切换到MySQL。

First, set the DB_CONNECTION, DB_HOST, DB_PORT, DB_DATABASE, DB_USERNAME, and DB_PASSWORD variables in your .env file.

首先,在.env文件中设置DB_CONNECTIONDB_HOSTDB_PORTDB_DATABASEDB_USERNAMEDB_PASSWORD变量。

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=<YOUR-DATABASE-NAME>
DB_USERNAME=<YOUR-DATABASE-USERNAME>
DB_PASSWORD=<YOUR-DATABASE-PASSWORD>

Next, add the following mysql key to the connections array in your config/database.php file.

接下来,将以下mysql键添加到config/database.php文件中的connections数组。

'mysql' => [
    'driver' => 'mysql',
    'host' => env('DB_HOST', 'localhost'),
    'port' => env('DB_PORT', '3306'),
    'database' => env('DB_DATABASE', 'forge'),
    'username' => env('DB_USERNAME', 'forge'),
    'password' => env('DB_PASSWORD', ''),
    'charset' => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix' => '',
    'strict' => false,
    'engine' => null,
],

And you are done!

您完成了!

MySQL vs SQLite-简要比较 ( MySQL vs SQLite - A Brief Comparision )

You can skim through countless articles and comparisions that conclude why MySQL is better than SQLite and vice versa but there is always a trade-off involved. As they say, use the right tools for the job as there is no one-size fits all in the field of Computer Sciences.

您可以浏览不计其数的文章和比较,这些文章和结论总结了为什么MySQL比SQLite更好,反之亦然,但是总要权衡取舍。 就像他们说的那样,使用正确的工具来完成这项工作,因为在计算机科学领域并没有一种合适的工具。

The table below compares both databases and will help you make the right call when embarking on your next project.

下表比较了这两个数据库,将在您开始下一个项目时帮助您做出正确的选择。

SQLiteMySQL
There is almost zero setup effort involved. All you need are the SQLite libraries. Deployment effort is minimal.The installation requires configuration so you should know your way around all the configuration variables involved. Deployment will require a similar execise in configuration.
It is suitable for standalone applications that run under single user setup like desktop and mobile applications.It is suitable for multiple users and highly concurrent applications.
When it comes to optimization, you cannot do much more than it's already amazing performance.There are a lot of options available for optimization if you wish to tinker with your setup.
No administration expertise required. All you need to do is backup your database file.Database administration is a vast area, so much so that some people make a career out of it.
You cannot manage user access and privileges as there are no user management features available.You can control user authentication and authorization at a very granular level.
SQLite的 MySQL
几乎零设置工作。 您需要的只是SQLite库。 部署工作量很小。 安装需要配置,因此您应该了解所涉及的所有配置变量。 部署将需要类似的配置执行。
它适用于在单个用户设置下运行的独立应用程序,例如台式机和移动应用程序。 它适用于多个用户和高度并发的应用程序。
当涉及到优化时,您不能做得比它已经令人惊讶的性能好得多。 如果您想修改设置,可以使用很多选项进行优化。
无需管理专业知识。 您需要做的就是备份数据库文件。 数据库管理是一个广阔的领域,以至于有些人以此为职业。
您无法管理用户访问权限和特权,因为没有可用的用户管理功能。 您可以在非常精细的级别上控制用户身份验证和授权。

将SQLite用于生产服务器 ( Using SQLite for Production Servers )

Before I comment on this, I would like to quote an excerpt from the official SQLite website.

在对此发表评论之前,我想引述SQLite官方网站的摘录。

SQLite works great as the database engine for most low to medium traffic websites (which is to say, most websites). The amount of web traffic that SQLite can handle depends on how heavily the website uses its database. Generally speaking, any site that gets fewer than 100K hits/day should work fine with SQLite. The 100K hits/day figure is a conservative estimate, not a hard upper bound. SQLite has been demonstrated to work with 10 times that amount of traffic.

对于大多数中低流量的网站(也就是说,大多数网站),SQLite可以很好地用作数据库引擎。 SQLite可以处理的网络流量取决于网站使用其数据库的程度。 一般来说,任何每天点击量少于10万的网站都可以在SQLite上正常运行。 每天10万次点击是一个保守的估计,而不是一个硬上限。 SQLite已被证明可以处理10倍的流量。

The SQLite website (https://www.sqlite.org/) uses SQLite itself, of course, and as of this writing (2015) it handles about 400K to 500K HTTP requests per day, about 15-20% of which are dynamic pages touching the database. Each dynamic page does roughly 200 SQL statements. This setup runs on a single VM that shares a physical server with 23 others and yet still keeps the load average below 0.1 most of the time.

SQLite网站( https://www.sqlite.org/ )当然使用SQLite本身,截至撰写本文(2015)时,它每天处理约40万至500K HTTP请求,其中约15-20%是动态的页面接触数据库。 每个动态页面大约执行200条SQL语句。 此设置在单个VM上运行,该VM与23个虚拟机共享一个物理服务器,但大多数情况下仍将平均负载保持在0.1以下。

As you can see, the argument mostly focuses on the number of users your application is engaged with. However, modern web application development is much more complex than just taking into account the traffic it serves.

如您所见,该参数主要集中在您的应用程序所涉及的用户数上。 但是,现代Web应用程序开发比仅仅考虑其服务的流量要复杂得多。

For a start, most of the web applications are deployed with a separate database user that is granted only as much privileges on the database as are required by the application. SQLite would fail this test alone as stated previously, there are no user management features available.

首先,大多数Web应用程序是使用单独的数据库用户部署的,该数据库用户仅被授予应用程序所需的数据库特权。 如前所述,SQLite将单独通过此测试,没有可用的用户管理功能。

最终裁决 ( The Final Verdict )

In this tutorial, you saw how easy it is to get Apache and MySQL out of the equation and quickly start prototyping your Laravel application with the built-in PHP server and SQLite.

在本教程中,您了解了使Apache和MySQL脱颖而出并快速开始使用内置PHP服务器和SQLite对Laravel应用程序进行原型设计的过程是多么容易。

Just as you would not use the PHP server in a production environment, you should not use SQLite in a production environment because of the limitations already discussed.

就像您不会在生产环境中使用PHP服务器一样,由于已经讨论过的限制,也不应在生产环境中使用SQLite。

This is a fast way to start tinkering away with a Laravel application. Then once you feel your application is ready for the bigger leagues, go ahead and switch over to MySQL.

这是开始修改Laravel应用程序的快速方法。 然后,一旦您感觉到您的应用程序已为更大的联盟做好了准备,请继续并切换到MySQL。

I hope you found this tutorial interesting and knowledgeable. Until my next piece, happy coding!

我希望您发现本教程有趣且知识丰富。 直到我的下一篇文章,祝您编程愉快!

翻译自: https://scotch.io/tutorials/prototype-quickly-in-laravel-with-phps-built-in-server-and-sqlite

内置表 sqlite

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值