Example of Unified Processing of Url Operations by Yii2 Framework Custom Classes

Time:2019-10-7

This paper illustrates the unified processing of URL operations by Yii2 framework custom classes. Share for your reference, as follows:

Because everyone writes URLs differently, it will be very troublesome for us to modify the URL later.

So we need to unify management, and we can also standardize writing.

1, newservices\UrlService.phpServices is our custom directory, dedicated to writing our various custom services.

<?php
namespace app\services;
use yii\helpers\Url;
/**
 * Unified management of links and standardized writing
 * Class UrlService
 * @package app\services
 */
class UrlService
{
  /**
   * Return an internal link
   * @param $uri
   * @param array $params
   * @return string
   */
  public static function buildUrl($uri,$params=[])
  {
    return Url::toRoute(array_merge([$uri],$params));
  }
  /**
   * Return an empty link
   * @return string
   */
  public static function buildNullUrl()
  {
    return "javascript:void(0)";
  }
}

2. We have written two static methods for the UrlService class. Let’s see how to use them.

Before we load JS and css, the code can be modified as follows:


$this->css = [
  UrlService::buildUrl("bootstrap/css/bootstrap.min.css",["v"=>$release]),
  UrlService::buildUrl('css/app.css')
];
$this->js = [
  UrlService::buildUrl('jquery/jquery.min.js'),
  UrlService::buildUrl('bootstrap/js/bootstrap.min.js')
];

3. At this time, we open the browser and find that the page is out of place. We have not successfully loaded CSS and js.

We need editorsconfig/web.phpThis configuration file opens the comments for the following code


'urlManager' => [
  'enablePrettyUrl' => true,
  'showScriptName' => false,
  'rules' => [
  ],
],

Readers interested in Yii-related content can see the topics of this site: Introduction to Yii Framework and Common Skills, Summary of Excellent Development Framework of php, Basic Course of Introduction to Smrty Template, Introduction to Php Object-Oriented Programming, Summary of Usage of Php String, Introduction to php+mysql Database Operations, and Common Database Operations of php. Summary of Skills

I hope that this article will be helpful to the PHP program design based on Yii framework.