最新消息:觉得本站不错的话 记得收藏哦 博客内某些功能仅供测试 讨论群:135931704 快养不起小站了 各位有闲钱就打赏下把 My Email weicots#gmail.com Please replace # with @

php 匿名函数[function() use(){}] 的应用场景 函数注入 并使组件重用

PHP ajiang-tuzi 4491浏览

应用场景



将一个流程固定为方法
并将 能使用由用户定义的函数来处理数据
此方法的主要功能
1. 获得任务
2.采集任务
3.同步任务

//我们可以发现这里面的 除了采集方法外 很多都是可以重用的 
//获得采集数据//
if ($taskTable->getSwitchStatus("spiderBeg")) {
    $taskList = $taskTable->getTaskList("0,30000", $WinTask["status"], $_ini["image_task"]["enabledGropTask"])->toArray();
    $i = 0;
    foreach ($taskList as $value) {
        $i++;
        echo "循环ID " . $i . "\t";
        if ($value["task_content"] == "") {
            $taskTable->upTaskStatus($value["fig"], "F");
            echo $value["fig"] . "\t" . $value["task_content"] . "\t错误 F \r\n";
            continue;
        }

        if ($Collection->getImageSave($value["task_content"], $ImageSaveDir)) {
            //跟新状态/
            $taskTable->upTaskStatus($value["fig"], "Y");
            //同步源数据/
            if ($taskTable->getSwitchStatus("syncOri")) {
                $taskTable->syncOriTable(
                    $taskTable->oriTable,
                    "local_image='" . $Collection->retrieve($value["task_content"]) . "'",
                    "ASIN='" . $value["fig"] . "'",
                    $value["fig"]
                );
            }
        } else {
            echo $value["fig"] . "\t" . $value["task_content"] . "\t错误 SP \r\n";
            $taskTable->upTaskStatus($value["fig"], "F");
        };

    }
}

将这个方法 抽像出来 使其可用通用

抽离成函数后


    function  runTaskContent($runAction)
    {
        $taskList = $this->taskTable->getTaskList(
            $this->limit,
            $this->taskTable->runStatus,
            $this->taskTable->grop
        )->toArray();
        $i = 0;
        foreach ($taskList as $value) {
            $i++;
            echo "循环ID " . $i . "\t";
            if ($value["task_content"] == "") {
                $this->taskTable->upTaskStatus($value["fig"], "F");
                echo $value["fig"] . "\t" . $value["task_content"] . "\t错误 F \r\n";
                continue;
            }
            //函数将在这里使用
            $returnAction = $runAction($value);
            if ($returnAction ) {
                //跟新状态/
                $this->taskTable->upTaskStatus($value["fig"], "Y");
                //同步源数据/
                if ($this->taskTable->getSwitchStatus("syncOri")) {
                    $this->taskTable->syncOriTable(
                        $this->taskTable->oriTable,
                        $returnAction["sync_set"],
                        $returnAction["sync_where"],
                        $returnAction["is_figid"]
                    );
                }
            } else {
                echo $value["fig"] . "\t" . $value["task_content"] . "\t错误 SP \r\n";
                $this->taskTable->upTaskStatus($value["fig"], "F");
            };

        }
    }

可以实现上面效果的其他方法

// 栗子
public function toHtml($block = false)
    {
        //在view 视图中创建块
        if (!$block) {
            $template = self::$template;
        } else {
            $template = self:: $createBlock;
        }
        foreach ($template as $value) {
            $blockName = explode('.', $value['blockName']);
            $blockValue = "Weicot\\" . $blockName[0] . "\\Block\\" . $blockName[1];
            $templatePath = BASE_PATH . DS . self::$templateDir . $value['templatePath'] . ".phtml";
            Debug::showPath($blockValue, $templatePath);
            if (file_exists($templatePath)) {
                $block = new $blockValue;
                if (isset($value['action']) && !empty($value['action'])) {
                    //判断是否初始化 block 函数
                    if (isset($value['value']) && !empty($value['value'])) {
                        $block->exe($value['action'], $value['value']);
                    } else {
                        $block->exe($value['action']);
                    }
                }
                require_once($templatePath);
            } else {
                echo "Template Not Found";
            }
        }

    }

WeiCot Framework 布局引擎
完整的使用代码

//这个  和上面的功能一样  只不过简化了许多步骤  使方法可以重用
//获得采集数据
if ($RunService->taskTable->getSwitchStatus("spiderBeg")) {
    $RunService->runTaskContent(function ($value) use ($RunService, $ImageSaveDir) {
        if ($RunService->Collection->getImageSave($value["task_content"], $ImageSaveDir)) {
            return [
                "sync_set" => "local_image='" . $RunService->Collection->retrieve($value["task_content"]) . "'",
                "sync_where" => "ASIN='" . $value["fig"] . "'",
                "is_figid" => $value["fig"]
            ];
        } else {
            return false;
        };
    });
}

完整代码介绍

<?php
/**
 * WeiCot Sp Framework
 * User: ajiang
 * WebSite: WWW.WEICOT.COM
 * Date: 2017/7/28 0028
 * Time: 17:25
 */
require_once dirname(__FILE__) . "/ini/bootstrap.php";
$_ini = $ini_sp;
use Weicot\Spider\RunService;

$RunService = new RunService();
$RunService->_ini($_ini, "image_task");  //使用配置文件种的  image_task 中数据配置以及基础配置
$RunService->setTaskIni([
    "grop" => $WinTask["grop"],
    "service" => $WinTask["service"],
    "limit" => $WinTask["limit"],
    "run_status" => $WinTask["status"]
]);

$RunService->Collection->setDirArry($_ini["image_task"]["path_array"]);  //设置分布式资源目录
$ImageSaveDir = $_ini["image_task"]["image_path"];   //文件保存目录
$RunService->taskTable->distinguishServiceId=false; //取消由多进程同步源表所分配的任务ID   方便重新分配任务表中任务


//同步数据
if ($RunService->taskTable->getSwitchStatus("importData")) {
    $sqlTask = 'select image,id  from ' .
        $RunService->taskTable->oriTable . ' where image<>"" and  islock="'
        . $_ini["image_task"]["ori_status"] . '" limit '
        . $WinTask["limit"];
    $selectData = $RunService->db->data($sqlTask);
    foreach ($selectData["data"] as $value) {
        $imageGrop = explode("|", $value["image"]);
        foreach ($imageGrop as $value2) {
            //添加进采集//
            $upStatusOri = 'UPDATE ' . $RunService->taskTable->oriTable . '  SET islock="Y" where id="' . $value["id"] . '";';
            if ($RunService->db->exe($upStatusOri)) {
                echo "Ori Data Lock\r\n";
            }
            $RunService->taskTable->addTask($value["id"], $value2);
        }
    }
}


//获得采集数据
if ($RunService->taskTable->getSwitchStatus("spiderBeg")) {
    $RunService->runTaskContent(function ($value) use ($RunService, $ImageSaveDir) {
        if ($RunService->Collection->getImageSave($value["task_content"], $ImageSaveDir)) {
            return [
                "sync_set" => "local_image='" . $RunService->Collection->retrieve($value["task_content"]) . "'",
                "sync_where" => "ASIN='" . $value["fig"] . "'",
                "is_figid" => $value["fig"]
            ];
        } else {
            return false;
        };
    });
}



参考 与引用匿名函数

转载请注明:(●--●) Hello.My Weicot » php 匿名函数[function() use(){}] 的应用场景 函数注入 并使组件重用

蜀ICP备15020253号-1