search
HomeBackend DevelopmentPHP TutorialMinor [PHP Framework] 3. Routing, controller, view, minor framework_PHP tutorial

Minor【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函数的第二个参数(['param1key' => 'param1value', 'param2key' => 'param2value' ...])就是向视图文件中传递的变量,我们可以在视图文件中使用这些变量:

文件:app/Modules/Demo/Controller/Tpl/Foo/bar.php<br /><?php echo $param1key;?><br /><?=$param2key ?>

  3.3.2 视图内置函数

  Minor提供了两个视图文件中可以使用的函数:

<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>

  这两个函数定义在app/Resource/functions.php文件中,你可以在这个文件中自定义你需要的视图函数。

 

3.4 响应

  可以在控制器中通过调用App对象的getMinorResponse()方法来获取当前MinorResponse对象。 MinorResponse类提供了六个方法分别是:

<span>public function send(); // 用于将响应对象发送给客户端

public function setHeader($header);// 设置响应头

public function setContent($content); // 设置响应对象的内容

public function beforeContent($content); // 在当前已有的内容之前添加内容

public function appendContent($content); // 在当前已有内容之后追加内容

public function getContent(); // 获取对象中的响应内容</span>

 

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1135100.htmlTechArticleMinor【 PHP框架】3.路由、控制器、视图,minor框架 3.1 路由 漂亮的URL绝对是一个严肃的web应用程序必须做到的,这种方式使index.php?article_id...
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
How does PHP identify a user's session?How does PHP identify a user's session?May 01, 2025 am 12:23 AM

PHPidentifiesauser'ssessionusingsessioncookiesandsessionIDs.1)Whensession_start()iscalled,PHPgeneratesauniquesessionIDstoredinacookienamedPHPSESSIDontheuser'sbrowser.2)ThisIDallowsPHPtoretrievesessiondatafromtheserver.

What are some best practices for securing PHP sessions?What are some best practices for securing PHP sessions?May 01, 2025 am 12:22 AM

The security of PHP sessions can be achieved through the following measures: 1. Use session_regenerate_id() to regenerate the session ID when the user logs in or is an important operation. 2. Encrypt the transmission session ID through the HTTPS protocol. 3. Use session_save_path() to specify the secure directory to store session data and set permissions correctly.

Where are PHP session files stored by default?Where are PHP session files stored by default?May 01, 2025 am 12:15 AM

PHPsessionfilesarestoredinthedirectoryspecifiedbysession.save_path,typically/tmponUnix-likesystemsorC:\Windows\TemponWindows.Tocustomizethis:1)Usesession_save_path()tosetacustomdirectory,ensuringit'swritable;2)Verifythecustomdirectoryexistsandiswrita

How do you retrieve data from a PHP session?How do you retrieve data from a PHP session?May 01, 2025 am 12:11 AM

ToretrievedatafromaPHPsession,startthesessionwithsession_start()andaccessvariablesinthe$_SESSIONarray.Forexample:1)Startthesession:session_start().2)Retrievedata:$username=$_SESSION['username'];echo"Welcome,".$username;.Sessionsareserver-si

How can you use sessions to implement a shopping cart?How can you use sessions to implement a shopping cart?May 01, 2025 am 12:10 AM

The steps to build an efficient shopping cart system using sessions include: 1) Understand the definition and function of the session. The session is a server-side storage mechanism used to maintain user status across requests; 2) Implement basic session management, such as adding products to the shopping cart; 3) Expand to advanced usage, supporting product quantity management and deletion; 4) Optimize performance and security, by persisting session data and using secure session identifiers.

How do you create and use an interface in PHP?How do you create and use an interface in PHP?Apr 30, 2025 pm 03:40 PM

The article explains how to create, implement, and use interfaces in PHP, focusing on their benefits for code organization and maintainability.

What is the difference between crypt() and password_hash()?What is the difference between crypt() and password_hash()?Apr 30, 2025 pm 03:39 PM

The article discusses the differences between crypt() and password_hash() in PHP for password hashing, focusing on their implementation, security, and suitability for modern web applications.

How can you prevent Cross-Site Scripting (XSS) in PHP?How can you prevent Cross-Site Scripting (XSS) in PHP?Apr 30, 2025 pm 03:38 PM

Article discusses preventing Cross-Site Scripting (XSS) in PHP through input validation, output encoding, and using tools like OWASP ESAPI and HTML Purifier.

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

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment