search
HomeBackend DevelopmentPHP TutorialLaravel Large Project Tutorial Series (6) Optimization, Unit Testing and Deployment

This tutorial will explain error handling, use of configuration files, unit testing and deployment to Apache server.

1. Error handling

If the URL visited by the user does not exist or there is an error in the server, we do not want to return an error page, but want to return a friendly prompt page, which can be easily implemented in Laravel, Laravel There is very simple error and log processing. When there is an error on the server side, there is an exception handler in app/start/global.php by default to handle all exceptions:

<code><span>App</span><span>::error(function(Exception</span> $<span>exception</span>)
<span>{
    <span><span>Log</span>:<span>:<span>error($exception)</span></span></span>;
<span>}</span></span>);</code>

It will write the exception information to the log, The default log file is app/storage/logs/laravel.log.

If we want to display a friendly error prompt page, we can create a view:

<code><span>$ </span>php artisan <span>generate:</span>view error</code>

Modify error.blade.php:

<code><span>@extends</span>(<span>'_layouts.default'</span>)

<span>@section</span>(<span>'main'</span>)
    Sorry, there <span>is</span> an error!
        <span>return</span> Index

<span>@stop</span></code>

Add in App::error(function(Exception $exception):

<code><span>return</span> Response<span>::view</span>(<span>'error'</span>, <span>array</span>(), <span>500</span>);</code>

Now when an access error occurs, an error prompt page will appear:

2.404 processing

When the accessed URL does not exist, we can also return a friendly prompt page, first create a view:

<code>$ php artisan generate:view <span>not</span><span>Found</span></code>

Modify notFound.blade.php:

<code><span>@extends</span>(<span>'_layouts.default'</span>)

<span>@section</span>(<span>'main'</span>)

    <span>Sorry</span>, the page you requested does <span>not</span> exist!
        <span>return</span><span>Index</span><span>@stop</span></code>

Add in app/start/global.php:

<code>App::missing(<span><span>function</span><span>(<span>$exception</span>)</span>
{</span><span>return</span> Response::view(<span>'notFound'</span>, <span>array</span>(), <span>404</span>);
});</code>

Now when the URL you visit does not exist, the following page will appear:

3. Configuration file

Sometimes we may need some values ​​that have been set in advance. When the program is executed, we only need to reference this value, such as the number displayed on each page when displaying in paging. We can use the configuration file, in Laravel It is also very convenient to use configuration files in app/config. We can create a new one named custom.php and add:

<code><span>return</span><span>array</span>(
    <span>'page_size'</span> => <span>10</span>,
);</code>

Now you can use it in the program, put paginate(10) Just change it to paginate(Config::get('custom.page_size'), where custom corresponds to the file name under app/config, page_size corresponds to the key name in the corresponding configuration file, and the configuration file also You can configure different configurations according to whether you are a development environment or a production environment. For details, you can view the official documentation.

4. Unit testing

Before the website goes online, we usually need to perform unit testing. Laravel provides a very convenient unit testing module. . I only implement an example here. We can first create a file named MyTest.php under app/tests and define a class named MyTest in it. Remember to inherit the TestCase class. Then you can write the test code:

<code><span><span>class</span><span>MyTest</span><span>extends</span><span>TestCase</span> {</span><span>public</span><span><span>function</span><span>testIndex</span><span>()</span>
    {</span><span>$this</span>->call(<span>'GET'</span>, <span>'/'</span>);
        <span>$this</span>->assertResponseOk();
        <span>$this</span>->assertViewHas(<span>'articles'</span>);
        <span>$this</span>->assertViewHas(<span>'tags'</span>);
    }

    <span>public</span><span><span>function</span><span>testNotFound</span><span>()</span>
    {</span><span>$this</span>->call(<span>'GET'</span>, <span>'test'</span>);
        <span>$this</span>->assertResponseStatus(<span>404</span>);
    }
}</code>

After the test code is written, we need to install a phpunit component, add it to require-dev in composer.json:

<code><span>"phpunit/phpunit"</span>: <span>"3.7.*"</span></code>

and then composer updateinstall it , execute vendor/bin/phpunit after completion, and the test results will appear after a while. If we want to do some initialization operations during our test, such as database migration and filling, etc., we can define it in the setUp method. , remember to execute parent::setUp first. If you want to restore the scene after the test is completed, you can do it in the tearDown method. If you want to use a specific configuration file during testing, we can do it in app/config Created in the /testing directory, it will automatically overwrite the original configuration during testing.

5. Deploy to Apache

After passing the test, we can deploy the website to the application server. In the production environment, we should set debug in app/config/app.php to false . Here we explain how to deploy to the Apache server. First of all, let me declare that the LAMP environment here is installed through tasksel. We first install the mod_rewrite module:

<code>$ <span>sudo</span> a2enmod rewrite</code>

and then set the permissions of the /var/www directory to 777. This directory is the directory where the website is stored. :

<code>$ sudo chmod -R <span>777</span> /<span>var</span><span>/www/</span></code>

Then copy the project folder we developed into this folder. Here is the blogfolder:

<code><span>$ </span>cd /var/www/
<span>$ </span>cp -r ~<span>/laravel-project/blog</span><span>/ .</span></code>

The above development project path must be the same as your own, and then we need to put app/ Change the permissions of the storage directory to 777, because the storage folder will store logs, etc., involving write operations:

<code><span>$ </span>cd blog/app/
<span>$ </span>chmod -<span>R</span><span>777</span> storage/</code>

Configure the server below:

<code>$ sudo vim /etc/apache2/sites-enabled/<span>000</span>-<span><span>default</span>.conf </span></code>

Change DocumentRoot/var/www/html to DocumentRoot /var/www/blog/public, then modify apache2.conf:

<code>$ <span>sudo</span> vim /etc/apache2/apache2.conf</code>

Add

<code>AllowOverride <span>all</span></code>

to

<code>Options Indexes FollowSymLinks
AllowOverride <span>None</span><span>Require</span><span>all</span> granted</code>

, now start the Apache server:

<code>$ <span>sudo</span> service apache2 start</code>

Visit localhost or in the browser 127.0.0.1You can see our website, and the deployment is complete.

6. Summary

本节教程讲了错误处理优化、配置文件的使用、单元测试以及怎么部署到Apache服务器,你可以买一个域名和一个服务器,最好买VPS云服务器,虚拟空间非常有局限性,然后把你自己写的网站部署到服务器让大家一起访问。

最后的代码下载:

<code><span>$ </span>git clone <span>https:</span>/<span>/github.com/shiyanlou</span><span>/laravel-blog-6.git</span></code>

本文详细出自http://www.shiyanlou.com/courses/123,转载请注明出处

以上就介绍了laravel大型项目系列教程(六)之优化、单元测试以及部署,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.