Example of Yii2 Framework Custom Classes Unified Handling of url Operations

  • 2021-12-11 17:30:42
  • OfStack

This article illustrates how the Yii2 Framework Custom Class 1 handles url operations. Share it for your reference, as follows:

Because everyone writes url in different ways, it will be very troublesome for us to modify url later.

Therefore, we need to unify 1 management and standardize writing at the same time.

1. Create services\ UrlService.php, services is our custom directory, which is specially used to write our various custom services.


<?php
namespace app\services;
use yii\helpers\Url;
/**
 *  Unified 1 Manage links and standardize writing 
 * Class UrlService
 * @package app\services
 */
class UrlService
{
  /**
   *  Return 1 Internal links 
   * @param $uri
   * @param array $params
   * @return string
   */
  public static function buildUrl($uri,$params=[])
  {
    return Url::toRoute(array_merge([$uri],$params));
  }
  /**
   *  Return 1 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 look at how to use them.

Before we load js and css, the code can be modified to read 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 opened the browser and found that the page was misplaced, and css and js were not successfully loaded.

We need to edit the config/web. php configuration file to open comments for the following code


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

For more readers interested in Yii related contents, please check the topics on this site: "Introduction to Yii Framework and Summary of Common Skills", "Summary of Excellent Development Framework of php", "Basic Tutorial of Introduction to smarty Template", "Introduction to php Object-Oriented Programming", "Summary of Usage of php String (string)", "Introduction to php+mysql Database Operation" and "Summary of Common Database Operation Skills of php"

Hope that this article is based on the framework of Yii PHP programming help.


Related articles: