


Minor [PHP Framework] 3. Routing, controller, view, minor framework_PHP tutorial
Jul 12, 2016 am 08:49 AMMinor【PHP Framework】3. Routing, controller, view, minor framework
3.1 Routing
Pretty URLs are an absolute must for a serious web application. This way ugly URLs like index.php?article_id=57 are hidden and replaced by more popular URLs like /read/intro-to -symfony instead.
3.1.1 Routing configuration
The configuration file is app/Config/routes.php
<?<span>php </span><span>return</span><span> [ </span>'/demo/{productName}' =><span> [ </span>'name' => 'test1', 'controller' => 'App\Modules\Demo\Controller\FooController', 'action' => 'bar', 'required' => ['productName' => '\w+'],<span> ]</span>,<span> ];</span>
Take the above code as an example to describe in detail how to configure an elegant (laravel disease...) routing
'/demo/{productName}' is the matching rule of routing. The required in the configuration specifies the regular conditions that productName must meet. During the actual operation of the framework, the routing rule required will be parsed into a regular expression/ demo/(w), when the url (eg: xxx.xxx.xxx/demo/testproduct) matches this regular rule, the action of the controller in the configuration will be executed. The specific execution is: FooController->bar($productName );
You can see that the content of the curly brackets (productName) in the routing rules is the parameter of the bar method. Therefore, when matching routes, be sure to note that the routing rules must be consistent with the number of parameters of the specific controller method, otherwise a ControllerException will be thrown.
3.1.2 Default routing configuration
If we have to configure a route every time we define a Controller, it will lead to low development efficiency. In order to prevent this problem from happening, Minor provides a default routing mechanism. When we visit http://xxx.xxx.xxx/demo/foo/bar, the bar method of AppModulesDemoFooController will be executed, that is, the default route is:
http://xxx.xxx.xxx/{module name}/{controller name}/{method name}
3.1.3 Disadvantages
As you can see, Minor’s routing is not powerful. Request method restrictions, HTTPS restrictions, and filters are not supported.
3.2 Controller
3.2.1 Create your own controller
The definition of Controller is very simple. Just inherit the MinorControllerController base class (of course you don’t have to inherit it, but the methods and properties in the base class cannot be used, which is easy to understand). First create the folder app/ Modules/Demo/Controller/, and then create the file FooController.php:
<?<span>php namespace App\Modules\Demo\Controller; </span><span>use</span><span> Minor\Controller\Controller; </span><span>//</span><span> 定義一個控制器</span> <span>class</span> FooController <span>extends</span><span> Controller { </span><span>//</span><span> 定義一個方法 </span> <span>public</span> <span>function</span><span> bar() { </span><span>return</span> 'Hello World'<span>; } }</span>
By accessing xxx.xxx.xxx/demo/foo/bar (default route, you can also configure your own route), you can see that Hello World is returned.
3.2.2 Url generation
Calling Url’s gen method can convert the default path to a URL that conforms to routing rules
<span>$url</span> = Url:gen(<span>$path</span>);
If Url::gen('/demo/foo/bar?productName=test') is configured according to the routing in 3.1.1, /demo/test will be returned.
3.2.3 Page jump redirect, redirect forward
Minor provides three jump methods: redirect, forward, and forwardUrl (these three are protected methods of MinorControllerController).
When jumping to another url, you can call it like this in the controller: $this->redirect($url);
When redirecting to another url, you can call it like this in the controller: $this->forwardUrl($url); (The implementation of this method is actually to parse out the controller and method of the url request through routing. Then call forward($controller, $action, $param))
When forwarding to another method, you can call it like this in the controller: $this->forward($controller, $action, $params); (The parameter $controller is the class name of the controller, including namespace)
Example:
<span>class</span> FooController <span>extends</span><span> Controller { </span><span>public</span> <span>function</span><span> bar() { </span><span>$this</span>->redirect('www.baidu.com'<span>); </span><span>return</span> <span>$this</span>->forward('App\Modules\Demo\Controller\FooController', 'bar', 'test'<span>); </span><span>return</span> <span>$this</span>->forward('/demo/testpro'<span>); } } </span>
3.2.4 Get request parameters
Call the get($paramName, $defaultParamValue = null) or post($paramName, $defaultParamValue = null) method of MinorRequest to get the request method. You can call it like this in the controller:
<span>class</span> FooController <span>extends</span><span> Controller { </span><span>public</span> <span>function</span><span> bar() { $minorRequest = <span>$this->app->getMinorRequest()</span>; </span><br /> $paramValue = <span>$minorRequest</span>->get('paramKey', 'defaultValue'<span>);<br /> ... } } </span>
3.2.5 Get request method
Call the getMethod() method of MinorRequest to get the requested method:
<span>class</span> FooController <span>extends</span><span> Controller { </span><span>public</span> <span>function</span><span> bar() { </span><span>$minorRequest</span> = <span>$this</span>->app-><span>getMinorRequest(); </span><span>$method</span> = <span>$minorRequest</span>-><span>getMethod(); </span>...<span> } } </span>
3.3 View
Minor provides an extremely powerful template engine. The name of this template engine is: PHP. Yes! You read that right, PHP. Why doesn't Minor provide a template engine like smarty or Twig? Because there is no need, PHP itself is good enough. If Minor builds a template engine, it will undoubtedly make it more difficult to use Minor, so Minor directly uses PHP as the language for view files.
3.3.1 Using views in controllers
To use a view in a controller, you only need to call View::render('module name:controller name:view file name', ['param1key' => 'param1value', 'param2key' => 'param2value' ...]); Example:
<span>class</span> FooController <span>extends</span><span> Controller { </span><span>public</span> <span>function</span><span> bar() { </span><span>$param1</span> = 'Hello'<span>; </span><span>$param2</span> = 'World'<span>; </span><span>return</span> View::render('Demo:Foo:bar.php', ['param1' => <span>$param1</span>, 'param2' => <span>$param2</span><span>]); } } </span>
render函數(shù)的第二個參數(shù)(['param1key' => 'param1value', 'param2key' => 'param2value' ...])就是向視圖文件中傳遞的變量,我們可以在視圖文件中使用這些變量:
文件:app/Modules/Demo/Controller/Tpl/Foo/bar.php<br /><?php echo $param1key;?><br /><?=$param2key ?>
3.3.2 視圖內置函數(shù)
Minor提供了兩個視圖文件中可以使用的函數(shù):
<span>function</span> include_tpl(<span>$module</span>, <span>$controller</span>, <span>$tpl</span><span>) { </span><span>require_once</span> (!<span>defined</span>('APP_DIR') ? APP_DIR : <span>realpath</span>(__DIR__ . '/../../app/') .DIRECTORY_SEPARATOR) . 'Modules' . '/' . <span>$module</span> . '/Tpl/' . <span>$controller</span> . '/' . <span>$tpl</span><span>; } </span><span>function</span> url(<span>$path</span><span>) { </span><span>return</span> Url::gen(<span>$path</span><span>); }</span>
使用:
<span>html> </span><span><?</span><span>php include_tpl('Public', 'Public', 'header.php');</span><span>?></span> <span><</span><span>body</span><span>></span> <span><</span><span>h1</span><span>></span>Hello!<span></</span><span>h1</span><span>></span> <span><</span><span>a </span><span>href</span><span>="<?php url('/demo/foo/bar?productName=testpro');?>"</span><span>></span> <span></</span><span>body</span><span>></span> <span></</span><span>html</span><span>></span>
這兩個函數(shù)定義在app/Resource/functions.php文件中,你可以在這個文件中自定義你需要的視圖函數(shù)。
3.4 響應
可以在控制器中通過調用App對象的getMinorResponse()方法來獲取當前MinorResponse對象?!inorResponse類提供了六個方法分別是:
<span>public function send(); // 用于將響應對象發(fā)送給客戶端 public function setHeader($header);// 設置響應頭 public function setContent($content); // 設置響應對象的內容 public function beforeContent($content); // 在當前已有的內容之前添加內容 public function appendContent($content); // 在當前已有內容之后追加內容 public function getContent(); // 獲取對象中的響應內容</span>
?

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The choice of PHP framework depends on project needs and developer skills: Laravel: rich in features and active community, but has a steep learning curve and high performance overhead. CodeIgniter: lightweight and easy to extend, but has limited functionality and less documentation. Symfony: Modular, strong community, but complex, performance issues. ZendFramework: enterprise-grade, stable and reliable, but bulky and expensive to license. Slim: micro-framework, fast, but with limited functionality and a steep learning curve.

There are differences in the performance of PHP frameworks in different development environments. Development environments (such as local Apache servers) suffer from lower framework performance due to factors such as lower local server performance and debugging tools. In contrast, a production environment (such as a fully functional production server) with more powerful servers and optimized configurations allows the framework to perform significantly better.

Benefits of combining PHP framework with microservices: Scalability: Easily extend the application, add new features or handle more load. Flexibility: Microservices are deployed and maintained independently, making it easier to make changes and updates. High availability: The failure of one microservice does not affect other parts, ensuring higher availability. Practical case: Deploying microservices using Laravel and Kubernetes Steps: Create a Laravel project. Define microservice controllers. Create Dockerfile. Create a Kubernetes manifest. Deploy microservices. Test microservices.

Integrating PHP frameworks with DevOps can improve efficiency and agility: automate tedious tasks, free up personnel to focus on strategic tasks, shorten release cycles, accelerate time to market, improve code quality, reduce errors, enhance cross-functional team collaboration, and break down development and operations silos

Best PHP Microservices Framework: Symfony: Flexibility, performance and scalability, providing a suite of components for building microservices. Laravel: focuses on efficiency and testability, provides a clean API interface, and supports stateless services. Slim: minimalist, fast, provides a simple routing system and optional midbody builder, suitable for building high-performance APIs.

The PHP framework extension library provides four frameworks for selection: Laravel: Known for its vast ecosystem and third-party packages, it provides authentication, routing, validation and other extensions. Symfony: Highly modular, extending functionality through reusable "Bundles", covering areas such as authentication and forms. CodeIgniter: lightweight and high-performance, providing practical extensions such as database connection and form validation. ZendFramework: Powerful enterprise-level features, with extensions such as authentication, database connection, RESTfulAPI support, etc.

Use a PHP framework to integrate artificial intelligence (AI) to simplify the integration of AI in web applications. Recommended framework: Laravel: lightweight, efficient, and powerful. CodeIgniter: Simple and easy to use, suitable for small applications. ZendFramework: Enterprise-level framework with complete functions. AI integration method: Machine learning model: perform specific tasks. AIAPI: Provides pre-built functionality. AI library: handles AI tasks.

The PHP framework is widely used in agile development and large-scale projects, providing advantages such as agility, scalability, and security. For example, in e-commerce websites, the Laravel framework can quickly create prototypes, handle complex business logic, ensure security, and extend functionality. By leveraging predefined components and design patterns, PHP frameworks facilitate developers to build scalable and well-maintained applications.
