dede extend.func.php 有何作用?如何使用?

99ANYc3cd6
预计阅读时长 24 分钟
位置: 首页 DEDE建站 正文

Of course. Let's break down extend.func.php, a very important file in the DedeCMS (织梦CMS) ecosystem.

dede extend.func.php
(图片来源网络,侵删)

What is extend.func.php?

In simple terms, extend.func.php is a custom function library for your DedeCMS website.

It's the primary place where you, the developer or site administrator, can add your own PHP functions to extend the core functionality of DedeCMS without modifying its core files.


The Core Concept: "Do Not Modify Core Files"

This is the golden rule of working with most Content Management Systems (CMS), including DedeCMS.

  • Why? When you update DedeCMS, the system will overwrite all the files in its core directory (like /include/). If you have modified a core file, your changes will be deleted, and your website may break.
  • The Solution: DedeCMS provides "safe" places to add custom code. extend.func.php is the most important of these for adding functions. It's designed to be included and loaded by the system on every page, so your custom functions are always available.

Where is it Located?

The file is typically found in the following directory:

dede extend.func.php
(图片来源网络,侵删)
/plus/extend.func.php

If it doesn't exist, you can simply create a new file with that name in the /plus/ directory.


How to Use It: A Step-by-Step Guide

Let's walk through a common example: creating a custom function to truncate text (shorten a string) while preserving HTML tags. DedeCMS has a built-in function for this, but let's imagine we want our own version.

Step 1: Create or Edit the File

Open or create /plus/extend.func.php in your favorite code editor.

Step 2: Add Your Custom Function

Add your PHP function to the file. It's good practice to prefix your function names to avoid conflicts with future DedeCMS updates or other plugins. A common prefix is yourname_ or site_.

dede extend.func.php
(图片来源网络,侵删)

Here is an example function myTruncHtml that safely truncates text:

<?php
if(!defined('DEDEINC')) exit('Request Error!');
/**
 * 安全截取包含HTML标签的字符串
 *
 * @param string $string 需要截取的字符串
 * @param int $length 截取长度
 * @param string $etc 结尾字符串,默认为 '...'
 * @param bool $breakword 是否在单词处断开,默认为 false
 * @return string
 */
function myTruncHtml($string, $length, $etc = '...', $breakword = false)
{
    $string = strip_tags($string); // 先去掉所有标签,确保长度计算准确
    if (strlen($string) > $length) {
        if ($breakword) {
            $length = strpos($string, ' ', $length);
        }
        if ($length === false) {
            $length = strlen($string);
        }
        $string = substr($string, 0, $length) . $etc;
    }
    return $string;
}

Explanation:

  • if(!defined('DEDEINC')) exit('Request Error!');: This is a standard security check in DedeCMS files. It ensures the file can only be executed within the DedeCMS environment and prevents direct access via a browser URL.
  • function myTruncHtml(...): This defines our custom function. We've named it myTruncHtml to be unique.
  • The rest of the code is the function's logic to truncate the string.

Step 3: Save the File

Save /plus/extend.func.php.

Step 4: Use Your Function in a Template

Now, you can call this function directly in any DedeCMS template file (.htm).

Let's say you have an article list and you want to show a short description of 200 characters.

In your template file (e.g., list_article.htm), you would use the function like this:

{dede:list pagesize='10'}
    <li>
        <a href="[field:arcurl/]">[field:title/]</a>
        <p>
            <!-- 调用我们自定义的函数来截取body内容 -->
            [field:body function='myTruncHtml(@me, 200)'/]
        </p>
    </li>
{/dede:list}

Explanation of the template call:

  • [field:body function='myTruncHtml(@me, 200)'/] is the key part.
  • field:body: This gets the value of the body field for the current article.
  • function='...': This tells DedeCMS to pass the field's value through a PHP function.
  • myTruncHtml(@me, 200): This calls our custom function.
    • @me is a special DedeCMS variable that represents the original value of the field (in this case, the full body text).
    • 200 is the first argument we are passing to our myTruncHtml function (the $length parameter).

Common Use Cases for extend.func.php

You can use this file to solve almost any custom development need. Here are some popular examples:

  1. Custom String Manipulation:

    • Truncate text with or without HTML tags (as shown above).
    • Convert text to uppercase, lowercase, or title case.
    • Remove special characters or spaces.
  2. Date and Time Formatting:

    • Create a function to display a "time ago" format (e.g., "2 hours ago", "3 days ago").
    • Format dates in a specific way not covered by DedeCMS's default options.
  3. Image Processing:

    • Create a function to automatically add a watermark to images.
    • Generate a thumbnail with specific dimensions on the fly.
    • Get the dimensions of an image without displaying it.
  4. Complex Logic for Fields:

    • Dynamically set a CSS class for an article based on its category ID.
    • Combine multiple field values into one output (e.g., {field:firstname} {field:lastname}).
    • Check if a user is logged in and display different content.
  5. Database Queries:

    • Create a function to fetch and display a list of the "most commented articles" from a custom query.
    • Pull data from a separate, external database table.

Best Practices

  • Prefix Your Functions: Always use a unique prefix (e.g., mywebsite_, clientname_) to prevent function name collisions.
  • Add Comments: Use PHPDoc () to comment your functions. This helps you (and others) remember what the function does, its parameters, and what it returns.
  • Validate Input: Inside your function, always validate and sanitize any input it receives to prevent security vulnerabilities like SQL injection or XSS attacks.
  • Keep it Organized: If you have many functions, you can split them into multiple files (e.g., text_functions.php, image_functions.php) and include them in extend.func.php using require_once().

Summary

Feature Description
Purpose To add custom PHP functions to DedeCMS safely.
Location /plus/extend.func.php
Key Benefit Allows you to extend functionality without modifying core files, ensuring your site remains update-safe.
Usage Define a function in extend.func.php.
Call it in templates using [field:xx function='myFunction(@me, param)'/].
Best Practice Use unique function names and comment your code.
-- 展开阅读全文 --
头像
织梦dedecms5.7栏目如何添加缩略图?
« 上一篇 12-01
dede config_base.php文件如何配置?
下一篇 » 12-01

相关文章

取消
微信二维码
支付宝二维码

目录[+]