首页 > 编程语言 >php 设计模式

php 设计模式

时间:2022-11-09 12:55:15浏览次数:48  
标签:function php class adaptee new curl 设计模式 public

<?php

//协程生成器函数并发
class Test
{
    public function async()
    {

        $start = microtime(true);
        $url = "https://money.finance.sina.com.cn/quotes_service/api/json_v2.php/CN_MarketData.getKLineData?symbol=";//随意的⼀个接⼝
        $i = 50;//假设请求N次
        $new_ids = ['sh601238', 'sh603280', 'sz000725', 'sz002594', 'sh601318', 'sh603359', 'sz000615', 'sz002460', 'sz003023', 'sh688621'];

        foreach ($new_ids as $new_id) {
            $gen[$new_id] = $this->_request("{$url}{$new_id}&scale=60&ma=60&datalen=1023");
            //实际应⽤中可能在多次请求之间有其他事情要处理,否则我们可以直接使⽤curl_multi
            //suppose i can do something here

        }
        $ret = $this->_dealGen($gen);
        var_export($ret);
        $end = microtime(true);
        echo $end - $start;

    }

    protected function _request($url)
    {

        $mh = curl_multi_init();
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_REFERER, 'https://finance.sina.com.cn/');//模拟来路
        curl_setopt($ch, CURLOPT_HEADER, 0); // no headers in the output
        curl_setopt($ch, CURLOPT_MAXREDIRS, 7);
        curl_multi_add_handle($mh, $ch);
        $active = null;
        do {
            $mrc = curl_multi_exec($mh, $active);
            //可以看到很多参考代码这⾥是sleep(),其实浪费了程序执⾏的时间
            yield null;//先去请求,不⽤等待结果
        } while ($active > 0);
        $raw = curl_multi_getcontent($ch);
        curl_multi_remove_handle($mh, $ch);
        curl_multi_close($mh);
        yield $raw;
    }

    protected function _dealGen($gens)
    {

        $ret = array();
        do {
            $running = false;
            foreach ($gens as $id => $gen) {
                if ($gen->valid()) {
                    //有任意没处理完的yield就继续进⾏处理
                    $running = true;
                    $gen->next();
                    $tmp = $gen->current();
                    if ($tmp !== null) {
                        $ret[$id] = $tmp;
                    }
                }
            }
        } while ($running);
        return $ret;
    }
}

//$test = new Test();
//$test->async();

//单例模式
class Singleton
{
    private static $_instance;
    private $num = 0;

    private function __construct()
    {
    }

    private function __clone()
    {
    }

    public function hello()
    {
        $this->num += 1;
        var_dump($this->num);
    }

    public static function getInstance()
    {
        if (!self::$_instance instanceof Singleton) {//instanceof 判断一个实例是否是某个类的对象
            self::$_instance = new Singleton();
        }
        return self::$_instance;
    }
}

//$a = Singleton::getInstance();
//$b = Singleton::getInstance();
//$c = Singleton::getInstance();
//$a->hello();
//$b->hello();
//$c->hello();

//工厂模式
class Factory
{
    public static function getInstance($newclass)
    {
        $class = $newclass;//真实项目中这里常常是用来解析路由,加载文件。
        return new $class;
    }
    //调用方法:Factory::getInstance(CLASS);
}

class A
{
}

class B
{
}

class C
{
}

//$a1=Factory::getInstance('A');
//$b1=Factory::getInstance('B');
//$c1=Factory::getInstance('C');
//var_dump($a1,$b1,$c1);

//注册模式
//创建单例
class Single
{
    public $hash;
    static protected $ins = null;

    final protected function __construct()
    {
        $this->hash = rand(1, 9999);
    }

    static public function getInstance()
    {
        if (self::$ins instanceof self) {
            return self::$ins;
        }
        self::$ins = new self();
        return self::$ins;
    }
}

//工厂模式
class RandFactory
{
    public static function factory()
    {
        return Single::getInstance();

    }
}

//注册树
class Register
{
    protected static $objects;

    public static function set($alias, $object)
    {
        self::$objects[$alias] = $object;
    }

    public static function get($alias)
    {
        return self::$objects[$alias];
    }

    public static function _unset($alias)
    {
        unset(self::$objects[$alias]);
    }
}

//调用
//Register::set('rand',RandFactory::factory());
//$object=Register::get('rand');print_r($object);

//策略模式
abstract class Strategy
{
    abstract function goSchool();
}

class Run extends Strategy
{
    public function goSchool()
    {
        // TODO: Implement goSchool() method.
    }
}

class Subway extends Strategy
{
    public function goSchool()
    {
        // TODO: Implement goSchool() method.
    }
}

class Bike extends Strategy
{
    public function goSchool()
    {
        // TODO: Implement goSchool() method.
    }
}

class Context
{
    protected $_stratege;//存储传过来的策略对象

    public function goSchoole()
    {
        $this->_stratege->goSchoole();
    }
}

//调用:
//$contenx = new Context();
//$avil_stratery = new Subway();
//$contenx->goSchoole($avil_stratery);

//适配器模式
abstract class Toy
{
    public abstract function openMouth();

    public abstract function closeMouth();
}

class Dog extends Toy
{
    public function openMouth()
    {
        echo "Dog open Mouth\n";
    }

    public function closeMouth()
    {
        echo "Dog close Mouth\n";
    }
}

class Cat extends Toy
{
    public function openMouth()
    {
        echo "Cat open Mouth\n";
    }

    public function closeMouth()
    {
        echo "Cat close Mouth\n";

    }
}

//目标角色(红)
interface RedTarget
{
    public function doMouthOpen();

    public function doMouthClose();
}

//目标角色(绿)
interface GreenTarget
{
    public function operateMouth($type = 0);
}

//类适配器角色(红)
class RedAdapter implements RedTarget
{
    private $adaptee;

    function __construct(Toy $adaptee)
    {
        $this->adaptee = $adaptee;
    }

    //委派调用Adaptee的sampleMethod1方法
    public function doMouthOpen()
    {
        $this->adaptee->openMouth();
    }

    public function doMouthClose()
    {
        $this->adaptee->closeMouth();
    }
}

//类适配器角色(绿)
class GreenAdapter implements GreenTarget
{
    private $adaptee;

    function __construct(Toy $adaptee)
    {
        $this->adaptee = $adaptee;
    }

    //委派调用Adaptee:GreenTarget的operateMouth方法
    public function operateMouth($type = 0)
    {
        if ($type) {
            $this->adaptee->openMouth();
        } else {
            $this->adaptee->closeMouth();
        }

    }
}

class testDriver
{
    public function run()
    {
        //实例化一只狗玩具
        $adaptee_dog = new Dog();
        echo "给狗套上红枣适配器\n";
        $adapter_red = new RedAdapter($adaptee_dog);
        //张嘴
        $adapter_red->doMouthOpen();
        //闭嘴
        $adapter_red->doMouthClose();
        echo "给狗套上绿枣适配器\n";
        $adapter_green = new GreenAdapter($adaptee_dog);
        //张嘴
        $adapter_green->operateMouth(1);
        //闭嘴
        $adapter_green->operateMouth(0);
    }
}

//调用
//$test = new testDriver();
//$test->run();

//观察者模式
// 主题接口
interface Subject
{

    public function register(Observer $observer);

    public function notify();
}

// 观察者接口
interface Observer
{

    public function watch();
}

// 主题
class Action implements Subject
{
    public $_observers = [];

    public function register(Observer $observer)
    {
        $this->_observers[] = $observer;
    }

    public function notify()
    {

        foreach ($this->_observers as $observer) {

            $observer->watch();

        }


    }
}

// 观察者
class Cat1 implements Observer
{

    public function watch()
    {

        echo "Cat1 watches TV<hr/>";

    }
}

class Dog1 implements Observer
{

    public function watch()
    {

        echo "Dog1 watches TV<hr/>";

    }

}

class People implements Observer
{

    public function watch()
    {

        echo "People watches TV<hr/>";

    }

}
// 调用实例
//$action=new Action();
//$action->register(new Cat1());
//$action->register(new People());
//$action->register(new Dog1());
//$action->notify();

 

标签:function,php,class,adaptee,new,curl,设计模式,public
From: https://www.cnblogs.com/bthuntergg/p/16873253.html

相关文章

  • [Kyana]服务器php+https配置
    00|前排提示本文涉及的apache、nginx和caddy三者并无优劣之分,各有擅场,在个人博客使用时选取自己喜欢的即可。如无特殊提示,本文默认环境为UbuntuServer20.04(Linux5.4)......
  • 【设计模式】689- TypeScript 设计模式之观察者模式
    一、模式介绍1.背景介绍在软件系统中经常碰到这类需求:当一个对象的状态发生改变,某些与它相关的对象也要随之做出相应的变化。这是建立一种「对象与对象之间的依赖关系」,......
  • 学习笔记-ThinkPHP 之 SQLI审计分析(三)
    ThinkPHP之SQLI审计分析(三)Time:9-23影响版本:ThinkPHP=5.1.22Payload:/public/index.php/index/index?orderby[id`|updatexml(1,concat(0x7,user(),0x7e),1)%23]=1......
  • 【设计模式】692- TypeScript 设计模式之发布-订阅模式
    前言在之前两篇自测清单中,和大家分享了很多JavaScript基础知识,大家可以一起再回顾下~本文是我在我们团队内部“「现代JavaScript突击队」”分享的一篇内容,第二期学习内......
  • 学习笔记-ThinkPHP5之SQLI审计分析(二)
    ThinkPHP之SQLI审计分析(二)Time:9-3影响版本:ThinkPHP=5.0.10Payload:/public/index.php/index/index?username[0]=notlike&username[1][0]=&username[1][1]=&userna......
  • 学习笔记-ThinkPHP5之SQLI审计分析(一)
    ThinkPHP5之SQLI审计分析(一)Time:8-31影响版本:5.0.13<=ThinkPHP<=5.0.15、5.1.0<=ThinkPHP<=5.1.5Payload:/public/index.php/index/index?username[0]=inc&username[1]=......
  • 设计模式学习(七):适配器模式
    设计模式学习(七):适配器模式作者:Grey原文地址:博客园:设计模式学习(七):适配器模式CSDN:设计模式学习(七):适配器模式适配器模式适配器模式是一种结构型模式。举例说明,假设有一......
  • 初识设计模式 - 中介模式
    简介中介设计模式(MediatorDesignPattern)定义了一个单独的(中介)对象,来封装一组对象之间的交互。如果对象之间存在大量的相互关联和调用,若有一个对象发生变化,则需要跟踪和......
  • 浅谈PHP设计模式的代理模式
    简介:代理模式,是结构型的设计模式。用于为其它对象提供一种代理以控制对这个对象的访问。目标对象可以是远程的对象、创建开销大的对象或需要安全控制的对象,并且可以在不......
  • CakePHP 2.x十分钟博客教程(二):控制器、模型与视图
     在上篇​​CakePHP教程​​中,为大家介绍了CakePHP的安装与配置过程。你的CakePHP框架现在应该已经能够建立应用程序了,本文为大家带来CakePHP如何创建控制器、模型及视图文......