php 部分缓存数据库返回数据的例子
$cache = new FileCache();
$new_arr = $cache->get('gsmcache');//yourkey是你为每一个要缓存的数据定义的缓存名字
if ($new_arr===false) {
$new_arr="数据库返回的数据";
$cache->set('gsmcache',$new_arr,3600);//缓存3600秒
}
<?php
/**
* 文件缓存类
*
* @copyright blog.itiwin.cn
* @author More
* @package cache
* @version v0.1
*/
class FileCache {
/**
* @var string $cachePath 缓存文件目录
* @access public
*/
public $cachePath = './';
/**
* 构造函数
* @param string $path 缓存文件目录
*/
function __construct($path = NULL) {
if ($path) {
$this->cachePath = $path;
}
}
/**
* 析构函数
*/
function __destruct() {
//nothing
}
/**
* 在cache中设置键为$key的项的值,如果该项不存在,则新建一个项
* @param string $key 键值
* @param mix $var 值
* @param int $expire 到期秒数
* @param int $flag 标志位
* @return bool 如果成功则返回 TRUE,失败则返回 FALSE。
* @access public
*/
public function set($key, $var, $expire = 36000, $flag = 0) {
$value = serialize($var);
$timeout = time() + $expire;
$result = safe_file_put_contents($this->cachePath . urlencode($key) .'.cache',
$timeout . '<<%-==-%>>' . $value);
return $result;
}
/**
* 在cache中获取键为$key的项的值
* @param string $key 键值
* @return string 如果该项不存在,则返回false
* @access public
*/
public function get($key) {
$file = $this->cachePath . urlencode($key) .'.cache';
if (file_exists($file)) {
$content = safe_file_get_contents($file);
if ($content===false) {
return false;
}
$tmp = explode('<<%-==-%>>', $content);
$timeout = $tmp[0];
$value = $tmp[1];
if (time()>$timeout) {
$this->delete($key) ;//删除文件过期的
$result = false;
} else {
$result = unserialize($value);
}
} else {
$result = false;
}
return $result;
}
/**
* 清空cache中所有项
* @return 如果成功则返回 TRUE,失败则返回 FALSE。
* @access public
*/
public function flush() {
$fileList = FileSystem::ls($this->cachePath,array(),'asc',true);
return FileSystem::rm($fileList);
}
/**
* 删除在cache中键为$key的项的值
* @param string $key 键值
* @return 如果成功则返回 TRUE,失败则返回 FALSE。
* @access public
*/
public function delete($key) {
return FileSystem::rm($this->cachePath . $key .'.cache');
}
}
if (!function_exists('safe_file_put_contents')) {
function safe_file_put_contents($filename, $content)
{
$fp = fopen($filename, 'wb');
if ($fp) {
flock($fp, LOCK_EX);
fwrite($fp, $content);
flock($fp, LOCK_UN);
fclose($fp);
return true;
} else {
return false;
}
}
}
if (!function_exists('safe_file_get_contents')) {
function safe_file_get_contents($filename)
{
$fp = fopen($filename, 'rb');
if ($fp) {
flock($fp, LOCK_SH);
clearstatcache();
$filesize = filesize($filename);
if ($filesize > 0) {
$data = fread($fp, $filesize);
}
flock($fp, LOCK_UN);
fclose($fp);
return $data;
} else {
return false;
}
}
}
通过php获取ip所属地的接口,要是自己弄一个ip库的话,会比较麻烦,而且需要经常更新,所以不现实。网上找了一些接口,发现好多都不能用了,于是自己写了一个,通过抓ip138页面来提取信息。只要它不改版,这个就能永久有效。
响应比较快,小网站用此接口完全没有问题,代码如下:
<?php
header("Content-type:text/html;charset=utf-8");
$ip = checkip(@$_GET['ip']);
if(!$ip)
{
exit( json_encode( array('error'=>1, 'msg'=>'参数ip不正确') ) );
}
$url = 'http://www.ip138.com/ips1388.asp?ip='.$ip.'&action=2';
$ipInfo = file_get_contents($url);
$ipInfo = iconv('gb2312', 'utf-8', $ipInfo);
preg_match('/<li>本站主数据:(.*)<\/li><li>/i', $ipInfo, $info);
if($info[1])
{
exit( json_encode( array('error'=>0, 'pos'=>$info[1]) ) );
}
else
{
exit( json_encode( array('error'=>1, 'msg'=>'解析失败') ) );
}
/**
* 验证ip格式是否正确
*/
function checkip($ip)
{
$ip = substr($ip, 0, 15); //ipv4最多只有这么长
if( !preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/', $ip) )
{
return false;
}
else
{
return $ip;
}
}
?>
访问形式为:localhost/ip.php?ip=xxx.xxx.xxx.xxx。带一个参数就行了,返回为json格式的数据
下面我们一直来看看magento2 添加支付方式payment method,有兴趣的可以和111cn小编一起来看看吧,希望例子对各位用。一:启动文件 \app\code\Inchoo\Stripe\etc\module.xml
<?xml version="1.0"?> <config xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance " xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd"> <module name="More_Payment" schema_version="1.0.0.0" active="true"> <sequence> <module name="Magento_Sales"/> <module name="Magento_Payment"/> </sequence> <depends> <module name="Magento_Sales"/> <module name="Magento_Payment"/> </depends> </module> </config>
二:配置文件config.xml \app\code\Inchoo\Stripe\etc\config.xml
<?xml version="1.0"?> <config xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance " xsi:noNamespaceSchemaLocation="../../../Magento/Core/etc/config.xsd"> <default> <payment> <more_payment> <active>1</active> <model>More\Payment\Model\Payment</model> <payment_action>authorize_capture</payment_action> <title>Payment</title> <api_key backend_model="Magento\Backend\Model\Config\Backend\Encrypted" /> <cctypes>AE,VI,MC,DI,JCB</cctypes> <allowspecific>1</allowspecific> <min_order_total>0.50</min_order_total> </more_payment> </payment> </default> </config>
三:后台配置文件 app\code\Inchoo\Stripe\etc\adminhtml\system2.xml
<?xml version="1.0"?> <config xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance " xsi:noNamespaceSchemaLocation="../../../../Magento/Backend/etc/system_file.xsd"> <system> <section id="payment" translate="label" type="text" sortOrder="400" showInDefault="1" showInWebsite="1" showInStore="1"> <group id="more_payment" translate="label" type="text" sortOrder="50" showInDefault="1" showInWebsite="1" showInStore="1"> <label>Payment</label> <field id="active" translate="label" type="select" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="0"> <label>Enabled</label> <source_model>Magento\Backend\Model\Config\Source\Yesno</source_model> </field> <field id="title" translate="label" type="text" sortOrder="2" showInDefault="1" showInWebsite="1" showInStore="1"> <label>Title</label> </field> <field id="api_key" translate="label" type="obscure" sortOrder="3" showInDefault="1" showInWebsite="1" showInStore="0"> <label>Api Key</label> <backend_model>Magento\Backend\Model\Config\Backend\Encrypted</backend_model> </field> <field id="debug" translate="label" type="select" sortOrder="4" showInDefault="1" showInWebsite="1" showInStore="0"> <label>Debug</label> <source_model>Magento\Backend\Model\Config\Source\Yesno</source_model> </field> <field id="cctypes" translate="label" type="multiselect" sortOrder="5" showInDefault="1" showInWebsite="1" showInStore="0"> <label>Credit Card Types</label> <source_model>More\Payment\Model\Source\Cctype</source_model> </field> <field id="sort_order" translate="label" type="text" sortOrder="100" showInDefault="1" showInWebsite="1" showInStore="0"> <label>Sort Order</label> </field> <field id="allowspecific" translate="label" type="allowspecific" sortOrder="50" showInDefault="1" showInWebsite="1" showInStore="0"> <label>Payment from Applicable Countries</label> <source_model>Magento\Payment\Model\Config\Source\Allspecificcountries</source_model> </field> <field id="specificcountry" translate="label" type="multiselect" sortOrder="51" showInDefault="1" showInWebsite="1" showInStore="0"> <label>Payment from Specific Countries</label> <source_model>Magento\Directory\Model\Config\Source\Country</source_model> </field> <field id="min_order_total" translate="label" type="text" sortOrder="98" showInDefault="1" showInWebsite="1" showInStore="0"> <label>Minimum Order Total</label> </field> <field id="max_order_total" translate="label" type="text" sortOrder="99" showInDefault="1" showInWebsite="1" showInStore="0"> <label>Maximum Order Total</label> <comment>Leave empty to disable limit</comment> </field> </group> </section> </system> </config>
四:model类 因为我们在config.xml配置了model,所以前台点击保存支付方式的时候 触发
<?php namespace More\Payment\Model; class Payment extends \Magento\Payment\Model\Method\Cc { const CODE = 'more_payment'; protected $_code = self::CODE; protected $_isGateway = true; protected $_canCapture = true; protected $_canCapturePartial = true; protected $_canRefund = true; protected $_canRefundInvoicePartial = true; protected $_stripeApi = false; protected $_minAmount = null; protected $_maxAmount = null; protected $_supportedCurrencyCodes = array('USD'); public function __construct( \Magento\Framework\Event\ManagerInterface $eventManager, \Magento\Payment\Helper\Data $paymentData, \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, \Magento\Framework\Logger\AdapterFactory $logAdapterFactory, \Magento\Framework\Logger $logger, \Magento\Framework\Module\ModuleListInterface $moduleList, \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate, \Magento\Centinel\Model\Service $centinelService, \Stripe\Api $stripe, array $data = array() ) { parent::__construct($eventManager, $paymentData, $scopeConfig, $logAdapterFactory, $logger, $moduleList, $localeDate, $centinelService, $data); $this->_stripeApi = $stripe; // $this->_stripeApi->setApiKey( // $this->getConfigData('api_key') // ); $this->_minAmount = $this->getConfigData('min_order_total'); $this->_maxAmount = $this->getConfigData('max_order_total'); } /** * 支付捕获方法 * * * @param \Magento\Framework\Object $payment * @param float $amount * @return $this * @throws \Magento\Framework\Model\Exception */ public function capture(\Magento\Framework\Object $payment, $amount) { /** @var Magento\Sales\Model\Order $order */ $order = $payment->getOrder(); /** @var Magento\Sales\Model\Order\Address $billing */ $billing = $order->getBillingAddress(); try { $charge = \Stripe_Charge::create(array( 'amount' => $amount * 100, 'currency' => strtolower($order->getBaseCurrencyCode()), 'description' => sprintf('#%s, %s', $order->getIncrementId(), $order->getCustomerEmail()), 'card' => array( 'number' => $payment->getCcNumber(), 'number' => $payment->getCcNumber(), 'exp_month' => sprintf('%02d',$payment->getCcExpMonth()), 'exp_year' => $payment->getCcExpYear(), 'cvc' => $payment->getCcCid(), 'name' => $billing->getName(), 'address_line1' => $billing->getStreet(1), 'address_line2' => $billing->getStreet(2), 'address_zip' => $billing->getPostcode(), 'address_state' => $billing->getRegion(), 'address_country' => $billing->getCountry(), ), )); $payment ->setTransactionId($charge->id) ->setIsTransactionClosed(0); } catch (\Exception $e) { $this->debugData($e->getMessage()); $this->_logger->logException(__('Payment capturing error.')); throw new \Magento\Framework\Model\Exception(__('Payment capturing error.')); } return $this; } /** * Payment refund * * @param \Magento\Framework\Object $payment * @param float $amount * @return $this * @throws \Magento\Framework\Model\Exception */ public function refund(\Magento\Framework\Object $payment, $amount) { $transactionId = $payment->getParentTransactionId(); try { \Stripe_Charge::retrieve($transactionId)->refund(); } catch (\Exception $e) { $this->debugData($e->getMessage()); $this->_logger->logException(__('Payment refunding error.')); throw new \Magento\Framework\Model\Exception(__('Payment refunding error.')); } $payment ->setTransactionId($transactionId . '-' . \Magento\Sales\Model\Order\Payment\Transaction::TYPE_REFUND) ->setParentTransactionId($transactionId) ->setIsTransactionClosed(1) ->setShouldCloseParentTransaction(1); return $this; } /** * Determine method availability based on quote amount and config data * * @param null $quote * @return bool */ public function isAvailable($quote = null) { if ($quote && ( $quote->getBaseGrandTotal() < $this->_minAmount || ($this->_maxAmount && $quote->getBaseGrandTotal() > $this->_maxAmount)) ) { return false; } // if (!$this->getConfigData('api_key')) { // return false; // } return parent::isAvailable($quote); } /** * Availability for currency * * @param string $currencyCode * @return bool */ public function canUseForCurrency($currencyCode) { if (!in_array($currencyCode, $this->_supportedCurrencyCodes)) { return false; } return true; } }
本文章来为各位介绍php中Yaf框架集成zendframework2的例子,有兴趣的可以和一聚教程小编一起来看看,具体操作如下。
php框架 Yaf集成zendframework2, zf2的orm 可以作为独立模块用到yaf中,而且zf2 composer service manger cacheStorage 都可以集成到yaf中。
一:public\index.php 加入composer
chdir(dirname(__DIR__)); // Decline static file requests back to the PHP built-in webserver if (php_sapi_name() === 'cli-server' && is_file(__DIR__ . parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH))) { return false; } // Setup autoloading require 'init_autoloader.php'; // Define path to application directory define("APP_PATH", dirname(__DIR__)); // Create application, bootstrap, and run $app = new Yaf_Application(APP_PATH . "/conf/application.ini"); $app->bootstrap()->run();
根目录 存放 init_autoloader.php
二:导入ZF2 模块组件
vendor\ZF2 见页尾下载包
三:更改bootstrap配置文件
<?php use Zend\ServiceManager\ServiceManager; use Zend\Mvc\Service\ServiceManagerConfig; use Zend\ModuleManager\Listener\ConfigListener; use Zend\ModuleManager\Listener\ListenerOptions; use Zend\ModuleManager\ModuleEvent; class Bootstrap extends Yaf_Bootstrap_Abstract { public function _initConfig() { $config = Yaf_Application::app()->getConfig(); Yaf_Registry::set("config", $config); } public function _initServiceManager() { $configuration = require APP_PATH . '/conf/application.config.php'; $smConfig = isset($configuration['service_manager']) ? $configuration['service_manager'] : array(); $serviceManager = new ServiceManager(new ServiceManagerConfig($smConfig)); $serviceManager->setService('ApplicationConfig', $configuration); $configListener = new ConfigListener(new ListenerOptions($configuration['module_listener_options'])); // If not found cache, merge config if (!$configListener->getMergedConfig(false)) $configListener->onMergeConfig(new ModuleEvent); // If enabled, update the config cache if ($configListener->getOptions()->getConfigCacheEnabled() && !file_exists($configListener->getOptions()->getConfigCacheFile())) { //echo "debug"; $configFile = $configListener->getOptions()->getConfigCacheFile(); $content = "<?php\nreturn " . var_export($configListener->getMergedConfig(false), 1) . ';'; file_put_contents($configFile, $content); } $serviceManager->setService('config', $configListener->getMergedConfig(false)); Yaf_Registry::set('ServiceManager', $serviceManager); } public function _initSessionManager() { Yaf_Registry::get('ServiceManager')->get('Zend\Session\SessionManager'); } public function _initPlugin(Yaf_Dispatcher $dispatcher) { $user = new UserPlugin(); $dispatcher->registerPlugin($user); } }
四:mvc测试
<?php use Zend\Session\Container as SessionContainer; use Zend\Db\TableGateway\TableGateway; class IndexController extends Yaf_Controller_Abstract { public function indexAction() { $adapter = $this->getDbAdapter(); $table = new TableGateway('zt_user', $adapter); $entities = $table->select(); foreach ($entities as $entity) { var_dump($entity->username); } $cache = $this->getStorage(); $cache->setItem('cache', 'cachedata'); echo $cache->getItem('cache'); $this->getLogger()->alert('log'); $this->getView()->assign("content", "Hello World"); } /** * db adapter * @return \Zend\Db\Adapter\Adapter */ public function getDbAdapter() { return Yaf_Registry::get('ServiceManager')->get('Zend\Db\Adapter\Adapter'); } /** * storage * @return \Zend\Cache\Storage\StorageInterface */ protected function getStorage() { return Yaf_Registry::get('ServiceManager')->get('Zend\Cache\Storage\StorageInterface'); } /** * logger * @return \Zend\Log\Zend\Log\Logger */ protected function getLogger() { return Yaf_Registry::get('ServiceManager')->get('Zend\Log\Logger'); } }
这样你访问public下的index.php 会输出hello word字样
1. xml标签要成对的书写,比如
<list><name>XXX</name><name>XXX</name></list>,而json写法是{"name":"XXX","name":"XXX"},
所以很明显json更节约传输的容量。
2. json生成和解析数据都比较简单,以php为例,只需用一个json_encode函数就可以将一个数组转为json数据了,而xml生成过程相对会麻烦一点。
3. json扩展比较方便,解析速度也较快一点。
所以项目中没有特别的规定,还是用json比较好。
相关文章
- 操作类就是把一些常用的一系列的数据库或相关操作写在一个类中,这样调用时我们只要调用类文件,如果要执行相关操作就直接调用类文件中的方法函数就可以实现了,下面整理了...2016-11-25
- 本文给大家分享C#连接SQL数据库和查询数据功能的操作技巧,本文通过图文并茂的形式给大家介绍的非常详细,需要的朋友参考下吧...2021-05-17
- 这篇文章主要介绍了C#从数据库读取图片并保存的方法,帮助大家更好的理解和使用c#,感兴趣的朋友可以了解下...2021-01-16
- 这篇文章主要介绍了mybatis-plus 返回部分字段的解决方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-10-02
- 这篇文章主要介绍了Intellij IDEA连接Navicat数据库的方法,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借价值,需要的朋友可以参考下...2021-03-25
- 在开发过程中,我们经常会将日期时间的毫秒数存放到数据库,但是它对应的时间看起来就十分不方便,我们可以使用一些函数将毫秒转换成date格式。 一、 在MySQL中,有内置的函数from_unixtime()来做相应的转换,使用如下: 复制...2014-05-31
- C#使用System.IO中的文件操作方法在Windows系统中处理本地文件相当顺手,这里我们还总结了在Oracle中保存文件的方法,嗯,接下来就来看看整理的C#操作本地文件及保存文件到数据库的基本方法总结...2020-06-25
- 通过内网连另外一台机器的mysql服务, 确发现速度N慢! 等了大约几十秒才等到提示输入密码。 但是ping mysql所在服务器却很快! 想到很久之前有过类似的经验, telnet等一些服务在连接请求的时候,会做一些反向域名解析(如果...2015-10-21
- 某些时候,例如为了搭建一个测试环境,或者克隆一个网站,需要复制一个已存在的mysql数据库。使用以下方法,可以非常简单地实现。假设已经存在的数据库名字叫db1,想要复制一份,命名为newdb。步骤如下:1. 首先创建新的数据库newd...2015-10-21
- mysqldump命令的用法1、导出所有库系统命令行mysqldump -uusername -ppassword --all-databases > all.sql 2、导入所有库mysql命令行mysql>source all.sql; 3、导出某些库系统命令行mysqldump -uusername -ppassword...2015-10-21
- 这篇文章主要介绍了node.js如何操作MySQL数据库,帮助大家更好的进行web开发,感兴趣的朋友可以了解下...2020-10-29
- 1005:创建表失败1006:创建数据库失败1007:数据库已存在,创建数据库失败1008:数据库不存在,删除数据库失败1009:不能删除数据库文件导致删除数据库失败1010:不能删除数据目录导致删除数据库失败1011:删除数据库...2013-09-23
- 这篇文章主要介绍了c#从数据库里取得数据并异步更新ui的方法,大家参考使用吧...2020-06-25
SQLMAP结合Meterpreter实现注入渗透返回shell
sqlmap 是一个自动SQL 射入工具。它是可胜任执行一个广泛的数据库管理系统后端指印, 检索遥远的DBMS 数据库等,下面我们来看一个学习例子。 自己搭建一个PHP+MYSQ...2016-11-25- yii2.0框架是PHP开发的一个比较高效率的框架,集合了作者的大量心血,下面通过用户为例给大家详解yii2使用中的一些基本的增删改查操作。 User::find()->all(); //返回所有用户数据; User::findOne($id); //返回 主键...2015-11-24
- 1.用phpmyadmin创建数据库和数据表 创建数据库的时候,请将“整理”设置为:“utf8_general_ci” 或执行语句: 复制代码 代码如下:CREATE DATABASE `dbname` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci; 创...2015-10-21
- 这篇文章主要介绍了springBoot 项目排除数据库启动方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-09-10
- 这篇文章主要介绍了Linux 下使用shell脚本定时维护数据库,本文通过案例分析给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-07-11
- 这篇文章主要介绍了Java连接数据库oracle中文乱码解决方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-05-16
- “主机,用户名,密码”得到连接、“数据库,sql,连接”得到结果,最后是结果的处理显示。当然,数据库连接是扩展库为我们完成的,我们能做的仅仅是处理结果而已。...2013-09-29