自定义php框架(phpcoco)

1.构建思路

路由 noahbuscher/macaw
数据模型 catfan/medoo
视图 twig/twig
分页应用库 jasongrimes/paginator
文件图片上传 brandonsavage/Upload
图片水印  Intervention/image
单个文件自动加载helpers.php

2.构建框路由

composer require noahbuscher/macaw:dev-master	

官方相关文件

https://github.com/noahbuscher/macaw

2.1在根目录下创建文件index.php,添加路由调用。如果还未设置自动路由需要手动composer dump-autoload

<?php
require('vendor/autoload.php');
use \NoahBuscher\Macaw\Macaw; //加载路由
Macaw::get('/', 'controllers\demo@index'); //案例
Macaw::get('page', 'controllers\demo@page');//案例
Macaw::get('view/(:num)', 'controllers\demo@view');//案例
Macaw::get('temp/lists', 'controllers\temp@lists');//案例
Macaw::dispatch();

3.自动加载控制器+单个文件加载

"autoload": {
    "psr-4": {
        "controllers\\": "app/controllers/", //自动加载控制器
        "models\\": "app/models/"
    },
    //这种模式需要手动加载执行composer dump-autoload
    "classmap": ["src/", "lib/", "Something.php"]
    "files": ["app/helpers.php"] //单个文件加载
   }

4.模板扩展加载 https://twig.symfony.com/doc/3.x/

composer require twig/twig:^2.12

4.1在控制器中创建Temp

<?php
namespace controllers;
class Temp
{
    public function lists(){
        $loader = new \Twig\Loader\FilesystemLoader('app/views');
        $twig = new \Twig\Environment($loader, [
            'cache' => '/path/to/compilation_cache',
        ]);
        $navigation = array(array('href'=>'www.baidu.com','caption'=>'百度'),array('href'=>'www.baidu.com','caption'=>'百度'));
        echo $twig->render('temp/lists.html', ['navigation' => $navigation]);
    }
}

4.2在模板文件app/views中传教temp/lists.html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<ul id="navigation">
    {% for item in navigation %}
    {{var_dump(item)}}
    <li><a href="{{ item.href }}">{{ item.caption }}</a></li>
    {% endfor %}
</ul>

<h1>My Webpage</h1>
{{ a_variable }}
</body>
</html>

4.3记得在index.php中添加路由

Macaw::get('temp/lists', 'controllers\temp@lists');

4.4效果图
在这里插入图片描述
4.5以上代码冗余过多,以下是优化为公共代码后,创建BaseController控制器,提炼出assign,display方法

<?php
namespace controllers;

class BaseController
{
    protected $twig;
    protected $data = array();
    public function __construct()
    {
        $loader = new \Twig\Loader\FilesystemLoader(dirname(__DIR__).'/views');
        $this->twig = new \Twig\Environment($loader,[]);
    }

    /**
     * @param $var
     * @param null $value
     */
    public function assign($var,$value=null){
        if (is_array($var)){
            $this->data = array_merge($this->data,$var);
        }else{
            $this->data[$var] = $value;
        }
    }

    /**
     * @throws \Twig\Error\LoaderError
     * @throws \Twig\Error\RuntimeError
     * @throws \Twig\Error\SyntaxError
     */
    public function display($template){
        echo $this->twig->render($template.'.html', $this->data);
    }
    public function success($url,$mess){
        echo "<script>";
        echo "alert('{$mess}')";
        echo "location.href='{$url}'";
        echo "</script>";
    }
    public function error($url,$mess){
        echo "<script>";
        echo "alert('error:{$mess}')";
        echo "location.href='{$url}'";
        echo "</script>";
    }
}

直接赋值

public function lists()
{
    $model = new TempDao();
    $navigation = $model->select('meiyou_admin', '*', ['nickname' => '测试']);
    $this->assign('navigation',$navigation);
    $this->display('temp/lists');

}

5.模型增加
官方文档https://github.com/catfan/Medoo

composer require catfan/medoo

案例,把temp中list方法的数据获取切换为以下代码,页面输出正常
//获取数据

$options = [
    'type' => 'mysql',
    'host' => '47.107.65.114',
    'database' => 'meinian',
    'username' => 'root',
    'password' => 'gqa123'
];
$model = new Medoo($options);
$navigation = $model->select('meiyou_admin',
    '*'
, [
    'nickname' => '测试'
]);

5.2优化代码创建BaseDao继承Medoo,同时需要增加composer配置

"autoload": {
    "psr-4": {
        "controllers\\": "app/controllers/",
        "models\\": "app/models/"  /
    },
    "files": ["app/helpers.php"]
<?php
namespace models;

use Medoo\Medoo;

class BaseDao extends Medoo
{
    function __construct()
    {
        $options = [
            'type' => 'mysql',
            'host' => '47.107.65.114',
            'database' => 'meinian',
            'username' => 'root',
            'password' => 'gqa123'
        ];
        parent::__construct($options);
    }
}


 <?php
namespace models;
class TempDao extends  BaseDao
{
    public function getList(){
        $data = $this->select('meiyou_admin','*', ['nickname' => '测试']);
       return $data;
    }
}

6.分页模型
https://github.com/jasongrimes/php-paginator

composer require "jasongrimes/paginator:~1.0"

7.图片上传
https://github.com/brandonsavage/Upload

//图片上传
composer require "codeguy/upload"  
//添加水印
composer require "Intervention/image"
``
在app文件夹下面传教uploader用于图片存储
案例代码如下在根目录下创建upload.html

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form method="POST" enctype="multipart/form-data" action="/temp/fileupload">
    <input type="file" name="foo" value=""/>
    <input type="submit" value="Upload File"/>
</form>
</body>
</html>

在temp控制器中添加方法
//注意 这个命名有重复需要用别名

use Intervention\Image\ImageManagerStatic as Image;
public function fileupload(){
        $path = dirname(__DIR__).'\uploader';
        $storage = new FileSystem($path);
        $file = new File('foo', $storage);
        // Optionally you can rename the file on upload
        $new_filename = uniqid();
        $file->setName($new_filename);

        // Validate file upload
        // MimeType List => http://www.iana.org/assignments/media-types/media-types.xhtml
        $file->addValidations(array(
            // Ensure file is of type "image/png"
            new Mimetype(array('image/png', 'image/gif','image/jpg','image/jpeg')),
            //You can also add multi mimetype validation
            //new \Upload\Validation\Mimetype(array('image/png', 'image/gif'))
            // Ensure file is no larger than 5M (use "B", "K", M", or "G")
            new Size('50M')
        ));
        // Access data about the file that has been uploaded
        $data = array(
            'name'       => $file->getNameWithExtension(),
            'extension'  => $file->getExtension(),
            'mime'       => $file->getMimetype(),
            'size'       => $file->getSize(),
            'md5'        => $file->getMd5(),
            'dimensions' => $file->getDimensions()
        );
        // Try to upload file
            $file_name =$path.'/'.$new_filename.'.'.$data['extension'];
        try {
            // Success!
            $file->upload();
            //添加水印裁剪
//            // open an image file
            $img = Image::make($file_name);
//            // resize image instance
            $img->resize(320, 240);
//            // insert a watermark
            $img->insert($path.'/watermark.gif');
//            // save image in desired format
            $img->save($path.'/'.$new_filename.'_1.'.$data['extension']);
        } catch (\Exception $e) {
            // Fail!
            $errors = $file->getErrors();
            dd($errors);
        }
    }

总结:
此框架还有许多为完善的地方后续会进一步更新,这是一个长期的过程,文中相关源码地址
https://github.com/hjklnmyuiop/phpcoco

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值