PHP的几个实用类

1.验证码类

<?php

/**
 * Created by PhpStorm.
 * User: guodong
 * Date: 2018/9/17
 * Time: 下午3:35
 */
class Code
{
    protected $type = '0';
    protected $width = 100;
    protected $height = 25;
    protected $length = 3;
    protected $image;
    protected $code;

    public function __construct()
    {
        $config = include 'config.php';
        $codeConfig = $config['code'];
        $this->setOptions($codeConfig);
        $this->getCode();
        $this->initImage();
        $this->oupPut();
    }

    protected function getCode()
    {
        switch ($this->type) {
            case 1:
                $code = $this->createChar($this->length);
                break;
            case 2:
                $code = $this->createCharNum($this->length);
                break;
            case 3:
                $code = $this->createNum($this->length);
                break;
            default:
                return false;
        }
        $this->code = $code;
    }

    protected function setOptions($config)
    {
        $vars = get_class_vars(get_class());
        $keys = array_keys($vars);
        foreach ($config as $key => $value) {
            if (in_array($key, $keys)) {
                $this->$key = $value;
            }
        }
    }

    protected function initImage()
    {
        $this->image = imagecreate($this->width, $this->height);
        $deepColor = $this->deepColor();
        imagefill($this->image, 0, 0, $deepColor);

        $width = $this->width / $this->length;

        for ($i = 0; $i < strlen($this->code); $i++) {
            $x = rand($i * $width + 10, ($i + 1) * $width - 10);
            $y = rand(0, $this->height/2);
            $color = $this->lightColor();
            imagechar($this->image,7,$x,$y,$this->code[$i],$color);
        }

        for ($i = 0; $i< 200 ;$i++) {
            $color = $this->lightColor();
            imagesetpixel($this->image,mt_rand(0,$this->width),mt_rand(0,$this->height),$color);
        }
    }

    protected function lightColor()
    {
       return  imagecolorallocate($this->image, rand(127, 255), rand(127, 255), rand(127, 255));
    }

    protected function deepColor()
    {
        return imagecolorallocate($this->image, rand(0, 127), rand(0, 127), rand(0, 127));
    }

    protected function createChar($length)
    {
        $str = join('', range('a', 'z'));
        $str .= join('', range('A', 'Z'));
        return substr(str_shuffle($str), 0, $length);
    }


    protected function createCharNum($length)
    {
        $str = join('', range('a', 'z'));
        $str .= join('', range('0', '9'));
        $str .= join('', range('A', 'Z'));
        return substr(str_shuffle($str), 0, $length);
    }

    protected function createNum($length)
    {
        $str = join('', range('0', '9'));
        return substr(str_shuffle($str), 0, $length);
    }

    public function __get($name)
    {
        if ($name == 'code'){
            return $this->code;
        }
        return false;
    }

    public function oupPut()
    {
        header('Content-type:image/png');
        imagepng($this->image);
    }

    public function __destruct()
    {
        imagedestroy($this->image);
    }
}
$code = new Code();

2.分页类

<?php

/**
 * Created by PhpStorm.
 * User: guodong
 * Date: 2018/9/17
 * Time: 下午11:40
 */
class Page
{

    protected $totalPage;
    protected $currentPage;
    protected $pageNum;
    protected $totalNum;

    public function __construct($totalNum, $pageNum)
    {
        $this->pageNum = $pageNum;
        $this->totalNum = $totalNum;
        $this->totalPage = ceil($this->totalNum / $this->pageNum);
        $this->currentPage = $this->getCurrentPage();
    }

    public function outPut()
    {
        $html = "";
        $parseData = parse_url($_SERVER['REQUEST_URI']);
        $path = $parseData['path'];
        $query = isset($parseData['query'])?:'';
        parse_str($query,$queryData);
        if (isset($parseData['page'])){
            unset($parseData['page']);
        }
        //$path = $path."?".http_build_query($queryData);

        for ($i = 1; $i <= $this->totalPage; $i++) {
            if ($i == $this->currentPage) {
                $title = "当前页";
            } elseif ($i == 1) {
                $title = "首页";
            } elseif ($i == $this->totalPage) {
                $title = "末页";
            } else {
                $title = "第{$i}页";
            }
            $queryData['page'] = $i;
            $url = $path."?".http_build_query($queryData);
            $html .= "<a href='$url' style='margin-left: 5px'>" . $title . "</a>";
        }
        return $html;
    }

    public function getCurrentPage()
    {
        if (isset($_GET['page']) && $page = $_GET['page']) {
            if ($page <= 1) {
                $this->currentPage = 1;
            } elseif ($page >= $this->totalPage) {
                $this->currentPage = $this->totalPage;
            } else {
                $this->currentPage = $page;
            }
        } else {
            $_GET['page'] = 1;
            $this->currentPage = 1;
        }
        return $this->currentPage;
    }

    public function getNextPage()
    {
        if ($this->currentPage + 1 <= $this->totalPage) {
            return $this->currentPage + 1;
        } else {
            return $this->totalPage;
        }
    }

    public function getPrePage()
    {
        if ($this->currentPage - 1 >= 1) {
            return $this->currentPage - 1;
        } else {
            return 1;
        }
    }

    public function getTotalPage()
    {
        return $this->totalPage;
    }
}

$page = new Page(37, 4);
echo $page->outPut();

3.模板引擎类

<?php

/**
 * Created by PhpStorm.
 * User: guodong
 * Date: 2018/9/18
 * Time: 上午12:55
 */
class Template
{
    protected $viewDir = './view/';
    protected $cacheDir = './cache/';
    protected $isCache = true;
    protected $expireTime = 60;
    protected $vars = [];
    protected $suffix = '.php';

    protected $rule = [
        '{$%%}' => '<?=$\1;?>',
        '{foreach %%}' => '<?php foreach(\1): ?>',
        '{/foreach}' => '<?php endforeach?>',
        '{include %%}' => '',
        '{if %%}' => '<?php if(\1):?>',
    ];

    public function assign($name, $data)
    {
        $this->vars[$name] = $data;
    }

    public function display($view = '', $isInclude = true)
    {
        $this->view = $view;
        $filePath = $this->getFilePath($view);
        $viewData = file_get_contents($filePath);
        $cachePath = $this->getCachePath($view);
        if (!file_exists($cachePath) || filectime($filePath) + $this->expireTime < time() || filemtime($filePath) > filemtime($cachePath)) {
            $data = $this->compile($viewData);
            file_put_contents($cachePath, $data);
        } else {
            $data = file_get_contents($cachePath);
        }
        if ($isInclude) {
            extract($this->vars);
            include $cachePath;
        }
        return $data;
    }

    protected function getFilePath($view)
    {
        return rtrim($this->viewDir, '/') . "/" . $view;
    }

    protected function getCachePath($view)
    {
        $str = $this->getFilePath($view) . $_SERVER['REQUEST_URI'];
        return rtrim($this->cacheDir, '/') . "/" . md5($str) . $this->suffix;
    }

    protected function compile($viewData)
    {
        foreach ($this->rule as $key => $value) {
            $pattern = str_replace("%%", "(.+?)", preg_quote($key, '#'));
            $pattern = "#$pattern#";
            if (strstr($pattern, 'include')) {
                $viewData = preg_replace_callback($pattern, [$this, 'parseInclude'], $viewData);
            } else {
                $viewData = preg_replace($pattern, $value, $viewData);
            }
        }
        return $viewData;
    }

    public function parseInclude($data)
    {
        $fileName = trim($data[1], '\'""');
        $this->display($fileName, false);
        $cachePath = $this->getCachePath($fileName);
        return '<?php include"' . $cachePath . '"?>"';
    }
}

作者:鸿雁长飞光不度
链接:https://www.jianshu.com/p/693299441bd2
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注