Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
知识付费系统
https://github.com/wlight/zsff
Admin
一个知识付费系统,提供内容上传(支持阿里云OSS)、短信服务(支持阿里云短信)以及便捷的安装和配置指南。
Tokens:
345,886
Snippets:
1,966
Trust Score:
4.5
Update:
11 months ago
Context
Chat
Benchmark
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### TypeScript Import and Basic Usage (axios) Source: https://github.com/wlight/zsff/blob/master/public/pc/plugins/axios/UPGRADE_GUIDE.md Demonstrates the recommended import statement for using axios in TypeScript projects targeting ES2015 module syntax. It includes a basic example of making a GET request and handling the response or error. ```typescript import axios from 'axios'; axios.get('/foo') .then(response => console.log(response)) .catch(error => console.log(error)); ``` -------------------------------- ### Install Alibaba Cloud Client for PHP via Composer Source: https://github.com/wlight/zsff/blob/master/vendor/alibabacloud/client/README.md Installs the Alibaba Cloud Client for PHP using Composer. Ensure Composer is installed globally. This is a prerequisite for using the client in your PHP project. ```bash composer require alibabacloud/client ``` -------------------------------- ### Install Axios using npm, bower, or yarn Source: https://github.com/wlight/zsff/blob/master/public/pc/plugins/axios/README.md Demonstrates how to install the Axios library using different package managers. This is the first step before using Axios in your project. ```bash npm install axios ``` ```bash bower install axios ``` ```bash yarn add axios ``` -------------------------------- ### Basic Socket Handler Setup in PHP Source: https://github.com/wlight/zsff/blob/master/vendor/monolog/monolog/doc/sockets.md Demonstrates how to configure and use the Monolog SocketHandler in PHP. This example shows creating a logger, initializing a persistent Unix socket handler, and pushing it to the logger to send log messages. ```php <?php use Monolog\Logger; use Monolog\Handler\SocketHandler; // Create the logger $logger = new Logger('my_logger'); // Create the handler $handler = new SocketHandler('unix:///var/log/httpd_app_log.socket'); $handler->setPersistent(true); // Now add the handler $logger->pushHandler($handler, Logger::DEBUG); // You can now use your logger $logger->addInfo('My logger is now ready'); ?> ``` -------------------------------- ### UMD Build Usage for Axios Source: https://github.com/wlight/zsff/blob/master/public/pc/plugins/axios/UPGRADE_GUIDE.md Shows examples of how to consume the Universal Module Definition (UMD) build of axios in different module environments, specifically AMD and CommonJS. ```javascript // AMD require(['bower_components/axios/dist/axios'], function (axios) { /* ... */ }); // CommonJS var axios = require('axios/dist/axios'); ``` -------------------------------- ### Install Alibaba Cloud OSS SDK PHP via Composer Source: https://github.com/wlight/zsff/blob/master/vendor/aliyuncs/oss-sdk-php/README.md Install the Alibaba Cloud OSS SDK for PHP using Composer package manager. This method declares the dependency in composer.json and requires running composer install. After installation, import the autoloader in your PHP code. ```bash composer require aliyuncs/oss-sdk-php ``` ```json "require": { "aliyuncs/oss-sdk-php": "~2.0" } ``` ```php require_once __DIR__ . '/vendor/autoload.php'; ``` -------------------------------- ### Install Alibaba Cloud OSS SDK PHP via PHAR or Source Source: https://github.com/wlight/zsff/blob/master/vendor/aliyuncs/oss-sdk-php/README.md Alternative installation methods for the Alibaba Cloud OSS SDK for PHP. Download the packaged PHAR file or source code and include the appropriate file in your PHP code to initialize the SDK. ```php require_once '/path/to/oss-sdk-php.phar'; ``` ```php require_once '/path/to/oss-sdk/autoload.php'; ``` -------------------------------- ### Install Workerman via Composer Source: https://github.com/wlight/zsff/blob/master/vendor/workerman/workerman/README.md Install the Workerman PHP package using Composer package manager. This command downloads and integrates Workerman into your project's vendor directory. ```bash composer require workerman/workerman ``` -------------------------------- ### Install Monolog using Composer Source: https://github.com/wlight/zsff/blob/master/vendor/monolog/monolog/README.md This command installs the latest version of the Monolog logging library for PHP using the Composer package manager. Ensure Composer is installed and accessible in your environment. ```bash composer require monolog/monolog ``` -------------------------------- ### Install PhpSpreadsheet using Composer Source: https://github.com/wlight/zsff/blob/master/vendor/phpoffice/phpspreadsheet/docs/index.md This command installs the PhpSpreadsheet library into your project using Composer. Ensure you have Composer installed and configured. ```sh composer require phpoffice/phpspreadsheet ``` -------------------------------- ### Install Pimple using Composer Source: https://github.com/wlight/zsff/blob/master/vendor/pimple/pimple/README.rst This command installs the Pimple library version 3.0 or higher using Composer, the dependency manager for PHP. It's the first step to using Pimple in your project. ```bash $ ./composer.phar require pimple/pimple "^3.0" ``` -------------------------------- ### Install jenssegers/date using Composer Source: https://github.com/wlight/zsff/blob/master/vendor/jenssegers/date/README.md This command installs the jenssegers/date library using Composer, the dependency manager for PHP. Ensure Composer is installed and accessible in your system's PATH. ```bash composer require jenssegers/date ``` -------------------------------- ### GET Request Source: https://github.com/wlight/zsff/blob/master/public/pc/plugins/axios/README.md Demonstrates how to perform a GET request to fetch data, including handling success and error responses, and using async/await. ```APIDOC ## GET /user ### Description Performs a GET request to retrieve user data based on an ID. ### Method GET ### Endpoint /user ### Parameters #### Query Parameters - **ID** (string) - Required - The ID of the user to retrieve. ### Request Example ```javascript axios.get('/user?ID=12345') .then(function (response) { // handle success console.log(response); }) .catch(function (error) { // handle error console.log(error); }); // Alternative with params object: axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); // Using async/await: async function getUser() { try { const response = await axios.get('/user?ID=12345'); console.log(response); } catch (error) { console.error(error); } } ``` ### Response #### Success Response (200) - **data** (any) - The data returned from the server. - **status** (number) - The HTTP status code. - **headers** (object) - The response headers. - **config** (object) - The request configuration. #### Response Example ```json { "data": { "id": 12345, "name": "John Doe" }, "status": 200, "headers": {}, "config": {} } ``` ``` -------------------------------- ### Install Carbon with Composer (CLI and JSON) Source: https://github.com/wlight/zsff/blob/master/vendor/nesbot/carbon/readme.md Provides instructions for installing the Carbon library using Composer. Includes the command-line instruction and the corresponding JSON configuration for the 'require' section of a composer.json file. ```bash composer require nesbot/carbon ``` ```json { "require": { "nesbot/carbon": "~1.21" } } ``` -------------------------------- ### Performing GET Requests with Axios Source: https://github.com/wlight/zsff/blob/master/public/pc/plugins/axios/README.md Shows various ways to perform GET requests using Axios. This includes basic requests with URL parameters, requests with a config object for parameters, and using async/await syntax for cleaner asynchronous handling. Error handling is demonstrated using `.catch()` and `try...catch` blocks. ```javascript const axios = require('axios'); // Make a request for a user with a given ID axios.get('/user?ID=12345') .then(function (response) { // handle success console.log(response); }) .catch(function (error) { // handle error console.log(error); }) .then(function () { // always executed }); // Optionally the request above could also be done as axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }) .then(function () { // always executed }); // Want to use async/await? Add the `async` keyword to your outer function/method. async function getUser() { try { const response = await axios.get('/user?ID=12345'); console.log(response); } catch (error) { console.error(error); } } ``` -------------------------------- ### Guzzle: Install with Composer (Bash) Source: https://github.com/wlight/zsff/blob/master/vendor/guzzlehttp/guzzle/README.md Provides the bash commands to install Composer and then use it to require the Guzzle HTTP client package for a PHP project. It also includes the command to update Guzzle later. ```bash # Install Composer curl -sS https://getcomposer.org/installer | php # Install Guzzle php composer.phar require guzzlehttp/guzzle # Update Guzzle composer.phar update ``` -------------------------------- ### TypeScript: Basic Axios GET Request Source: https://github.com/wlight/zsff/blob/master/public/pc/plugins/axios/README.md Provides a basic example of making a GET request using Axios with TypeScript definitions. This showcases the import statement and a simple GET call to retrieve user data. ```typescript import axios from 'axios'; axios.get('/user?ID=12345'); ``` -------------------------------- ### GET Function Example in PHP Source: https://github.com/wlight/zsff/blob/master/vendor/phpoffice/phpspreadsheet/docs/topics/calculation-engine.md Demonstrates using the GET function to retrieve a value from a database based on specified criteria. It involves setting up a worksheet with database and criteria arrays, then calling the GET function and retrieving the calculated value. ```php $database = [ [ 'Tree', 'Height', 'Age', 'Yield', 'Profit' ], [ 'Apple', 18, 20, 14, 105.00 ], [ 'Pear', 12, 12, 10, 96.00 ], [ 'Cherry', 13, 14, 9, 105.00 ], [ 'Apple', 14, 15, 10, 75.00 ], [ 'Pear', 9, 8, 8, 76.80 ], [ 'Apple', 8, 9, 6, 45.00 ], ]; $criteria = [ [ 'Tree', 'Height', 'Age', 'Yield', 'Profit', 'Height' ], [ '="=Apple"', '>10', NULL, NULL, NULL, '<16' ], [ '="=Pear"', NULL, NULL, NULL, NULL, NULL ], ]; $worksheet->fromArray( $criteria, NULL, 'A1' ) ->fromArray( $database, NULL, 'A4' ); $worksheet->setCellValue('A12', '=GET(A4:E10,"Age",A1:F2)'); $retVal = $worksheet->getCell('A12')->getCalculatedValue(); // $retVal = 14 ``` -------------------------------- ### Configure Page Scaling Options (PHP) Source: https://github.com/wlight/zsff/blob/master/vendor/phpoffice/phpspreadsheet/docs/topics/recipes.md Provides examples of how to control the scaling options for a worksheet's page setup in PhpSpreadsheet. This includes fitting content to a specific width or height, and adjusting the scale percentage, mimicking Excel's 'Page Setup' dialog. ```php $spreadsheet->getActiveSheet()->getPageSetup()->setFitToWidth(1); $spreadsheet->getActiveSheet()->getPageSetup()->setFitToHeight(0); ``` -------------------------------- ### Serve PhpSpreadsheet samples locally Source: https://github.com/wlight/zsff/blob/master/vendor/phpoffice/phpspreadsheet/docs/index.md This command starts a local PHP development server to serve the PhpSpreadsheet samples. Navigate to http://localhost:8000 in your browser to view them. ```sh php -S localhost:8000 -t vendor/phpoffice/phpspreadsheet/samples ``` -------------------------------- ### Install and Use JMESPath PHP Library Source: https://github.com/wlight/zsff/blob/master/vendor/mtdowling/jmespath.php/README.rst Demonstrates basic installation via Composer and fundamental usage of the JMESPath search function to extract nested JSON elements. The example shows how to require the autoloader and execute a JMESPath expression against PHP array data structures. ```php require 'vendor/autoload.php'; $expression = 'foo.*.baz'; $data = [ 'foo' => [ 'bar' => ['baz' => 1], 'bam' => ['baz' => 2], 'boo' => ['baz' => 3] ] ]; JmesPath\search($expression, $data); // Returns: [1, 2, 3] ``` -------------------------------- ### Handle Course Toggle and Playback Logic (JavaScript) Source: https://github.com/wlight/zsff/blob/master/application/wap/view/first/special/text_detail.html Manages the logic when a course is toggled, including checks for payment status, free courses, and trial periods. If a course requires purchase, it prompts the user to buy. Otherwise, it retrieves a task link and initiates playback or navigation to course details. Dependencies include Axios, layer for confirmations, and potentially window location for redirection. ```javascript courseToggle: function (course) { var vm = this; if (course.id == taskId) { return; } if (!this.isPay && course.is_free && !course.is_try) { return layer.confirm('购买后可操作,是否购买?', { title: false, closeBtn: false, btn: ['购买', '取消'] }, function (index) { layer.close(index); vm.dialogOpen = false; vm.payDialogOpen = true; vm.taskIdClicked = course.id; }); } this.dialogOpen = false; taskId = course.id; axios.get("{:url('special/get_task_link')}", { params: { task_id: taskId, special_id: specialId } }).then(function (res) { if (res.data.code === 200) { axios.get("{:url('special/play_num')}", { params: { task_id: taskId, special_id: specialId } }).then(function (res) { if (res.data.code === 200) { if (course.type == 1) { vm.getTaskInfo(); } else { window.location.assign("{:url('special/task_info')}?id=" + course.id + '&specialId=' + course.special_id + '&viewing_time=' + (course.watch && course.watch.viewing_time || 0)); } } }); } }); } ``` -------------------------------- ### Manage Live Streaming with Aliyun Integration Source: https://context7.com/wlight/zsff/llms.txt Handles the creation and management of live streaming studios, including integration with Aliyun Live. It supports generating push/pull URLs, recording playback, and enabling real-time interaction via WebSockets. Dependencies include `LiveStudio`, `LivePlayback` models, and Workerman for WebSocket communication. Inputs are studio details and playback information. Outputs include live stream URLs and updated studio status. ```php // Create and manage live streaming studio // Location: application/admin/model/live/LiveStudio.php // Create live studio $studioData = [ 'special_id' => 123, // Associated course ID 'title' => 'Advanced PHP Live', // Studio title 'cover_img' => 'https://...', // Cover image URL 'teacher_id' => 456, // Teacher/lecturer ID 'start_time' => strtotime('2024-01-15 19:00:00'), 'end_time' => strtotime('2024-01-15 21:00:00'), 'stream_name' => 'live_stream_123', // Unique stream identifier 'live_type' => 1, // 1=Aliyun Live, 2=other 'is_show' => 1, // 1=visible, 0=hidden 'is_del' => 0, // Soft delete flag 'mer_id' => 0, // Merchant ID (0=platform) ]; // Generate Aliyun Live push and pull URLs $liveInfo = LiveStudio::create($studioData); // Push URL (for broadcasting): // rtmp://push.example.com/live/live_stream_123?auth_key=[timestamp]-[rand]-[uid]-[md5hash] // Pull URLs (for viewing): $playUrls = [ 'rtmp' => "rtmp://pull.example.com/live/{$stream_name}", 'flv' => "http://pull.example.com/live/{$stream_name}.flv", 'm3u8' => "http://pull.example.com/live/{$stream_name}.m3u8" ]; // Record live session for playback $playbackData = [ 'live_id' => $liveInfo['id'], 'video_id' => 'aliyun_video_abc123', // Aliyun VOD video ID 'title' => 'Session 1 - Introduction', 'cover' => 'https://...', 'duration' => 7200, // Duration in seconds 'size' => 524288000, // File size in bytes 'create_time' => time() ]; LivePlayback::create($playbackData); // Get live studio with playback list $studio = LiveStudio::with('playback')->where('id', $liveInfo['id'])->find(); // Start live streaming (update status) LiveStudio::where('id', $liveInfo['id'])->update([ 'status' => 1, // 0=not started, 1=live, 2=ended 'actual_start_time' => time() ]); // Real-time interaction via WebSocket (Workerman) // Location: application/push/ directory // WebSocket server on port 20014, Channel on 20015 // Client connects to WebSocket for real-time features: // - Live chat messages // - Real-time viewer count // - Barrage/bullet comments // - Gift animations // ws://your-domain.com:20014 ``` -------------------------------- ### Stringy::between Method Example in PHP Source: https://github.com/wlight/zsff/blob/master/vendor/danielstjules/stringy/README.md Shows the Stringy::between() method, which extracts and returns the substring located between the first occurrences of specified start and end delimiters. It returns an empty string if the delimiters are not found. An optional offset can specify the starting position for the search. Assumes PHP 5.6+ function importing. ```php s('{foo} and {bar}')->between('{', '}'); // 'foo' ``` -------------------------------- ### Fetch Product Reviews Source: https://github.com/wlight/zsff/blob/master/application/wap/view/first/store/detail.html Retrieves a list of product reviews from the server. It handles pagination and checks if all reviews have been loaded. The fetched reviews are appended to the existing list. ```javascript // 获取评价列表 getEvaluateList: function () { var vm = this; if (this.finished) { return false; } api.baseGet($h.U({ c: 'auth\_api', a: 'product\_reply\_list', q: { productId: this.storeInfo.id, score: this.score, page: this.page++, limit: this.limit } }), function (res) { var data = res.data.data; vm.evaluateList = vm.evaluateList.concat(data); vm.finished = vm.limit > data.length; }); } ``` -------------------------------- ### Vue.js Initialization and Component Setup Source: https://github.com/wlight/zsff/blob/master/application/wap/view/first/merchant/teacher_detail.html Initializes a Vue.js application, registers components like BaseLogin, and sets up initial data, computed properties, and watchers. It also handles event listening for touch direction and scroll events. This code is executed within a require.js callback. ```javascript require(['vue', 'helper', 'store', 'components/base-login/index', 'quick'], function (Vue, $h, store, BaseLogin) { var isWechat = {$isWechat? 'true': 'false'}; var uid = {$uid}; var site_name = "{$Auth_site_name}"; var spread_uid = "{$spread_uid}"; new Vue({ el: '#app', components: { 'base-login': BaseLogin }, data: { lecturer: {$lecturer}, business: {$business}, merId: {$mer_id}, extract: 0, today: 0, total: 0, gold: 0, navList: [ { name: '简介', value: 1 }, { name: '专题', value: 2 }, { name: '资料', value: 3 }, { name: '活动', value: 4 }, { name: '商品', value: 5 }, { name: '练习', value: 6 }, { name: '考试', value: 7 }, ], navActive: 1, page: 1, limit: 16, list: [], finished: false, isFixed: false, ticking: false, isFollow: false, loginShow: false, site_name: site_name, spread_uid: spread_uid, problemPage: 1, problemList: [], problemFinished: false, questionPage: 1, questionList: [], questionFinished: false }, computed: { navCurrent: function () { for (var i = 0; i < this.navList.length; i++) { if (this.navList[i].value === this.navActive) { return this.navList[i].name; } } } }, watch: { navActive: function (value) { this.page = 1; this.list = []; this.finished = false; switch (value) { case 2: this.lecturer_special_list(); break; case 3: this.lecturer_download_list(); break; case 4: this.lecturer_event_list(); break; case 5: this.lecturer_store_list(); break; case 6: this.getProblemList(); break; case 7: this.getQuestionList(); break; } } }, created: function () { var vm = this; this.lecturer_income(); this.getIsFollow(); if (isWechat) { mapleWx($jssdk(), function () { this.onMenuShareAll({ title: vm.lecturer.lecturer_name, desc: vm.lecturer.label.join(), imgUrl: vm.lecturer.lecturer_head, link: window.location.href + (window.location.search ? '&' : '?') + 'spread_uid=' + uid }); }); } $h.EventUtil.listenTouchDirection(document, function () { switch (vm.navActive) { case 2: vm.lecturer_special_list(); break; case 3: vm.lecturer_download_list(); break; case 4: vm.lecturer_event_list(); break; case 5: vm.lecturer_store_list(); break; case 6: vm.getProblemList(); break; case 7: vm.getQuestionList(); break; } }); window.addEventListener('scroll', function () { if (!vm.ticking) { window.requestAnimationFrame(function () { vm.ticking = false; vm.isFixed = document.documentElement.scrollTop >= vm.offsetTop; }); } vm.ticking = true; }); store.baseGet("{:url('index/login_user')}", undefined, undefined, true); }, mounted: function () { this.$nextTick(function () { this.offsetTop = this.$refs.nav.offsetTop; }) }, methods: { // 讲师名下课程 lecturer_special_list: function () { var vm = this; if (this.finished) { return; } $h.loadFFF(); store.baseGet($h.U({ c: 'merchant', a: 'lecturer_special_list', q: { mer_id: this.lecturer.mer_id, page: this.page, limit: this.limit } }), function (res) { $h.loadClear(); var data = res.data.data; vm.list = vm.list.concat(data); vm.finished = vm.limit > data.length; }); }, // 讲师名下资料 lecturer_download_list: function () { var vm = this; if (this.finished) { return; } $h.loadFFF(); store.baseGet($h.U({ c: 'merchant', a: 'lecturer_download_list', q: { mer_id: this.lecturer.mer_id, page: this.page, limit: this.limit } }), function (res) { $h.loadClear(); var data = res.data.data; vm.list = vm.list.concat(data); vm.finished = vm.limit > data.length; }); }, // 讲师名下活动 lecturer_event_list: function () { var vm = this; if (this.finished) { return; } $h.loadFFF(); store.baseGet($h.U({ c: 'merchant', a: 'lecturer_event_list', q: { mer_id: this.lecturer.mer_id, page: this.page, limit: this.limit } }), function (res) { $h.loadClear(); var data = res.data.data; vm.list = vm.list.concat(data); vm.finished = vm.limit > data.length; }); }, // 讲师名下商品 lecturer_store_list: function () { var vm = this; if (this.finished) { return; } $h.loadFFF(); store.baseGet($h.U({ c: 'merchant', a: 'lecturer_store_list', q: { mer_id: this.lecturer.mer_id, page: this.page, limit: this.limit } }), function (res) { $h.loadClear(); var data = res.data.data; vm.list = vm.list.concat(data); vm.finished = vm.limit > data.length; }); }, // 收益及提现统计 lecturer_income: function () { var vm = this; store.baseGet($h.U({ c: 'merchant', a: 'lecturer_income', q: { mer_id: this.lecturer.mer_id } }), function (res) { var data = res.data.data; vm.extract = data.extract; vm.today = data.today; vm.total = data.total; vm.gold = data.gold; }); }, getIsFollow: function () { var vm = this; store.baseGet($h.U({ c: 'merchant', a: 'is_follow', q: { mer_id: this.lecturer.mer_id } }), function (res) { vm.isFollow = res.data.data.code; }); }, // 关注 follow: function () { var vm = this; store.baseGet("{:url('index/login_user')}", function () { store.baseGet("{:url('merchant/user_follow')}?mer_id=" + vm.lecturer.mer_id + '&is_follow=' + Number(!vm.isFollow), function (res) { vm.isFollow = !vm.isFollow; $h.pushMsg(vm.isFollow ? '关注成功' : '取消关注成功'); }); }, function () { // Handle login or other error cases }); } } }); }); ``` -------------------------------- ### Creating an Axios Instance Source: https://github.com/wlight/zsff/blob/master/public/pc/plugins/axios/README.md Demonstrates how to create a custom Axios instance with predefined configurations, such as base URL and timeout. ```APIDOC ## axios.create([config]) ### Description Creates a new Axios instance with a custom configuration. This is useful for setting default options like `baseURL`, `timeout`, or custom headers that will apply to all requests made with this instance. ### Method `axios.create(config)` ### Parameters #### `config` Object - **baseURL** (string) - Optional - The base URL for requests. - **timeout** (number) - Optional - Timeout in milliseconds. - **headers** (object) - Optional - Default headers. ### Request Example ```javascript const instance = axios.create({ baseURL: 'https://some-domain.com/api/', timeout: 1000, headers: {'X-Custom-Header': 'foobar'} }); // Now use the instance to make requests: instance.get('/users') .then(function (response) { console.log(response.data); }); ``` ### Instance Methods Instances created with `axios.create` have the same methods as the global Axios object (e.g., `get`, `post`, `request`), but they will use the instance's configuration. The specified config will be merged with the instance config. ``` -------------------------------- ### Basic Carbon Usage with Composer Autoload (PHP) Source: https://github.com/wlight/zsff/blob/master/vendor/nesbot/carbon/readme.md A simple PHP script demonstrating how to include Composer's autoloader and use the Carbon library to get the current date and time. Requires the Carbon package to be installed via Composer. ```php <?php require 'vendor/autoload.php'; use Carbon\Carbon; printf("Now: %s", Carbon::now()); ``` -------------------------------- ### Create WebServer with Virtual Hosts Source: https://github.com/wlight/zsff/blob/master/vendor/workerman/workerman/README.md Set up a WebServer on port 80 with 4 worker processes supporting multiple virtual hosts. Maps domain names to their respective document root directories for serving static and dynamic content. ```php require_once __DIR__ . '/vendor/autoload.php'; use Workerman\WebServer; use Workerman\Worker; // WebServer $web = new WebServer("http://0.0.0.0:80"); // 4 processes $web->count = 4; // Set the root of domains $web->addRoot('www.your_domain.com', '/your/path/Web'); $web->addRoot('www.another_domain.com', '/another/path/Web'); // run all workers Worker::runAll(); ``` -------------------------------- ### Async Redis Connection with ReactPHP and Workerman (PHP) Source: https://github.com/wlight/zsff/blob/master/vendor/workerman/workerman/README.md Utilizes ReactPHP's Redis client within a Workerman application for asynchronous Redis operations. This example connects to a Redis server, performs set, append, and get operations, and increments a counter. ```bash composer require clue/redis-react ``` ```php <?php require_once __DIR__ . '/vendor/autoload.php'; use Clue\React\Redis\Factory; use Clue\React\Redis\Client; use Workerman\Worker; $worker = new Worker('tcp://0.0.0.0:6161'); $worker->onWorkerStart = function() { global $factory; $loop = Worker::getEventLoop(); $factory = new Factory($loop); }; $worker->onMessage = function($connection, $data) { global $factory; $factory->createClient('localhost:6379')->then(function (Client $client) use ($connection) { $client->set('greeting', 'Hello world'); $client->append('greeting', '!'); $client->get('greeting')->then(function ($greeting) use ($connection){ // Hello world! echo $greeting . PHP_EOL; $connection->send($greeting); }); $client->incr('invocation')->then(function ($n) use ($connection){ echo 'This is invocation #' . $n . PHP_EOL; $connection->send($n); }); }); }; Worker::runAll(); ``` -------------------------------- ### Update Chart Rendering Configuration to PhpOffice PhpSpreadsheet Source: https://github.com/wlight/zsff/blob/master/vendor/phpoffice/phpspreadsheet/docs/topics/migration-from-PHPExcel.md Demonstrates the updated method for configuring the JpGraph chart renderer in PhpSpreadsheet. It shows the older method using a string path and the new method using a class constant after dependency installation via composer. ```sh composer require jpgraph/jpgraph ``` ```php Settings::setChartRenderer(PhpOffice\PhpSpreadsheet\Chart\Renderer\JpGraph::class); ``` -------------------------------- ### Vue JS Initialization and Data Fetching for Group Courses (JavaScript) Source: https://github.com/wlight/zsff/blob/master/application/wap/view/first/my/order_list.html Initializes a Vue.js application to manage the display and interaction of group purchase courses. It fetches course data using a helper function and handles user interactions like inviting others or proceeding to course details. Dependencies include Vue, helper, store, and quick modules. ```JavaScript require(['vue', 'helper', 'store', 'quick'], function (Vue, helper, store) { var vm = new Vue({ el: '#app', data: { page: 1, limit: 16, list: [], finished: false }, created: function () { this.getList(); helper.EventUtil.listenTouchDirection(document, function () { vm.getList(); }); }, methods: { // 列表信息 getList: function () { if (this.finished) { return; } helper.loadFFF(); store.baseGet(helper.U({ c: 'my', a: 'get_order_list', q: { page: this.page++, limit: this.limit, type: 3 } }), function (res) { var list = res.data.data.list; helper.loadClear(); vm.list = vm.list.concat(list); vm.finished = vm.limit > list.length; }, function (err) { helper.pushMsg(err.data.msg); }); }, // 点击邀请参团 invite: function (item) { if (item.pink_status != 4) { window.location.href = helper.U({ c: 'special', a: 'pink', q: { pink_id: item.pink_id, special_id: item.cart_id, is_help: 0 } }); } }, // 点击去学习、重新开团 goSpecial: function (item) { window.location.href = (item.is_light ? "{:url('special/single_details')}" : "{:url('special/details')}") + '?id=' + item.cart_id; } } }); }); ``` -------------------------------- ### Get Calculated Value from Cell Formula in PHP Source: https://github.com/wlight/zsff/blob/master/vendor/phpoffice/phpspreadsheet/docs/topics/calculation-engine.md Retrieves the evaluated result of a formula stored in a cell using PhpSpreadsheet. This method evaluates formulas like SUM(A1:A10) and returns the numeric result. The example demonstrates calling getCalculatedValue() on cell E11 which evaluates to 64. ```PHP $spreadsheet->getActiveSheet()->getCell('E11')->getCalculatedValue(); ``` -------------------------------- ### Stringy::at Method Example in PHP Source: https://github.com/wlight/zsff/blob/master/vendor/danielstjules/stringy/README.md Illustrates the Stringy::at() method, which returns the character at a given index within the string. Indexes start at 0. This method is useful for accessing individual characters based on their position. Assumes PHP 5.6+ function importing. ```php s('fòôbàř')->at(3); // 'b' ``` -------------------------------- ### Initialize OSSClient for Alibaba Cloud OSS Source: https://github.com/wlight/zsff/blob/master/vendor/aliyuncs/oss-sdk-php/README.md Create and initialize an OSSClient object using access credentials and endpoint URL. This client instance is used to perform all OSS operations. Exception handling with OssException is recommended for error management. ```php <?php $accessKeyId = "<AccessKeyID that you obtain from OSS>"; $accessKeySecret = "<AccessKeySecret that you obtain from OSS>"; $endpoint = "<Domain that you select to access an OSS data center, such as \"oss-cn-hangzhou.aliyuncs.com\">"; try { $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint); } catch (OssException $e) { print $e->getMessage(); } ``` -------------------------------- ### Get Calculated Value from PHPExcel Formula Cell Source: https://github.com/wlight/zsff/blob/master/vendor/phpoffice/phpexcel/Documentation/markdown/Overview/09-Calculation-Engine.md Retrieves the calculated result of a formula contained in a specific cell using PHPExcel's getCalculatedValue() method. This evaluates the formula and returns the computed value. In the invoice demo example, the formula in cell E11 evaluates to 64. ```php $objPHPExcel->getActiveSheet()->getCell('E11')->getCalculatedValue(); ``` -------------------------------- ### Create Alibaba Cloud Client Instance in PHP Source: https://github.com/wlight/zsff/blob/master/vendor/alibabacloud/client/README.md Demonstrates how to create an Alibaba Cloud client instance using access keys in PHP. This client is then used to send requests to Alibaba Cloud services. ```php <?php use AlibabaCloud\Client\AlibabaCloud; AlibabaCloud::accessKeyClient('accessKeyId', 'accessKeySecret')->asDefaultClient(); ``` -------------------------------- ### Run JMESPath PHP Tests with Make Commands Source: https://github.com/wlight/zsff/blob/master/vendor/mtdowling/jmespath.php/README.rst Provides commands for executing test suites in jmespath.php using Make. Includes standard unit tests via PHPUnit and performance benchmarks. Requires prior Composer installation of dependencies. ```bash make test ``` ```bash make perf ``` -------------------------------- ### Set odd header and footer in PHPExcel Source: https://github.com/wlight/zsff/blob/master/vendor/phpoffice/phpexcel/Documentation/markdown/Overview/08-Recipes.md Configure header and footer text for a worksheet using setOddHeader() and setOddFooter() methods. Supports formatting codes (starting with &) for dynamic content like page numbers, dates, and document properties. The example sets a confidential notice in the header and document title with page numbering in the footer. ```php $objPHPExcel->getActiveSheet()->getHeaderFooter() ->setOddHeader('&C&HPlease treat this document as confidential!'); $objPHPExcel->getActiveSheet()->getHeaderFooter() ->setOddFooter('&L&B' . $objPHPExcel->getProperties()->getTitle() . '&RPage &P of &N'); ``` -------------------------------- ### Vue Component Initialization and Data Setup Source: https://github.com/wlight/zsff/blob/master/application/wap/view/first/special/single_text_detail.html Initializes a Vue instance with payment-related data properties, component imports, and lifecycle hooks. Manages payment dialog state, user payment methods, and product content display. Dependencies include Vue, helper utilities, HTTP store, and PayDialog component. ```JavaScript require(['vue', 'helper', 'store', 'components/pay-dialog/index'], function (Vue, $h, $http, PayDialog) { var vm = new Vue({ el: '#app', components: { 'pay-dialog': PayDialog }, data: { title: '', profile: {}, content: { isPay: true }, id: id, isTry: '', payDialogOpen: false, now_money: now_money, isWechat: isWechat, is_alipay: is_alipay, is_yue: is_yue, templateIds: '', wxpayH5: wxpayH5, memberLink: memberLink }, created: function () { this.getDetail(); }, mounted: function () { this.$nextTick(function () { document.body.style.paddingTop = this.$refs.header.clientHeight + 'px'; }); } }); }); ``` -------------------------------- ### Making a Generic Request Source: https://github.com/wlight/zsff/blob/master/public/pc/plugins/axios/README.md Provides an example of making a request using the base `axios(config)` method, allowing for full customization of request parameters. ```APIDOC ## axios(config) ### Description Allows for making HTTP requests with a fully customizable configuration object. ### Method Any valid HTTP method (e.g., POST, GET, PUT, DELETE) ### Endpoint Specified in the `url` property of the config. ### Parameters #### Request Body (for methods like POST, PUT, PATCH) - **data** (any) - Required/Optional - The data to send in the request body. #### Other Config Properties - **method** (string) - The HTTP method (e.g., 'get', 'post'). - **url** (string) - The endpoint URL. - **params** (object) - URL parameters. - **headers** (object) - Custom headers. - **responseType** (string) - The type of response (e.g., 'json', 'stream'). ### Request Example ```javascript // Send a POST request axios({ method: 'post', url: '/user/12345', data: { firstName: 'Fred', lastName: 'Flintstone' } }); // GET request for remote image in node.js axios({ method: 'get', url: 'http://bit.ly/2mTM3nY', responseType: 'stream' }) .then(function (response) { // Handle stream }); ``` ### Response #### Success Response - **data** (any) - The response data. - **status** (number) - The HTTP status code. - **headers** (object) - The response headers. - **config** (object) - The request configuration. #### Response Example ```json { "data": "Response content", "status": 200, "headers": {}, "config": {} } ``` ``` -------------------------------- ### Install weblibs-configmanager via Composer Source: https://github.com/wlight/zsff/blob/master/vendor/clagiordano/weblibs-configmanager/README.md Install the weblibs-configmanager library using Composer package manager. This is the recommended installation method for integrating the library into your PHP project. ```bash composer require clagiordano/weblibs-configmanager ``` -------------------------------- ### Fetch Course List using Axios (JavaScript) Source: https://github.com/wlight/zsff/blob/master/application/wap/view/first/special/text_detail.html Fetches a list of courses for a special topic using an asynchronous GET request with Axios. It handles successful responses by updating the course list and setting a finished flag, and manages loading states. Dependencies include Axios for HTTP requests and potentially a layer loading indicator. ```javascript axios.get("{:url('special/get_course_list')}", { params: { special_id: this.specialId, page: this.page++, limit: this.limit } }).then(function (res) { if (res.data.code === 200) { var data = res.data.data; var list = []; if (!Array.isArray(data)) { list = data.list; } vm.courseList = vm.courseList.concat(list); vm.finished = list.length < vm.limit; } else { } }).catch(function (err) { }).then(function () { vm.loading = false; }); ``` -------------------------------- ### Set Cell Values and Calculate DATEVALUE in PhpSpreadsheet Source: https://github.com/wlight/zsff/blob/master/vendor/phpoffice/phpspreadsheet/docs/topics/calculation-engine.md Demonstrates how to set date string values in cells and use the DATEVALUE formula to convert them to Excel date format (serial numbers). Shows configuration of return date type to RETURNDATE_EXCEL to get numeric date values like 39813.0. This example validates that different date string formats all convert to the same serial number. ```php $worksheet->setCellValue('A1', 'Date String'); ->setCellValue('A2', '31-Dec-2008') ->setCellValue('A3', '31/12/2008') ->setCellValue('A4', '12-31-2008'); $worksheet->setCellValue('B2', '=DATEVALUE(A2)') ->setCellValue('B3', '=DATEVALUE(A3)') ->setCellValue('B4', '=DATEVALUE(A4)'); \PhpOffice\PhpSpreadsheet\Calculation\Functions::setReturnDateType( \PhpOffice\PhpSpreadsheet\Calculation\Functions::RETURNDATE_EXCEL ); $retVal = $worksheet->getCell('B2')->getCalculatedValue(); $retVal = $worksheet->getCell('B3')->getCalculatedValue(); $retVal = $worksheet->getCell('B4')->getCalculatedValue(); // $retVal = 39813.0 for all cases ``` -------------------------------- ### Axios Configuration Precedence Example Source: https://github.com/wlight/zsff/blob/master/public/pc/plugins/axios/README.md Demonstrates how Axios merges configuration settings. It shows that library defaults are overridden by instance defaults, which are in turn overridden by request-specific configurations. This ensures the most specific configuration is applied. ```javascript const instance = axios.create(); // Override timeout default for the library // Now all requests using this instance will wait 2.5 seconds before timing out instance.defaults.timeout = 2500; // Override timeout for this request as it's known to take a long time instance.get('/longRequest', { timeout: 5000 }); ``` -------------------------------- ### Bower Installation Command Source: https://github.com/wlight/zsff/blob/master/public/pc/plugins/require-css/README.md Provides the command to install the `require-css` package using the Bower package manager. Bower is a popular choice for front-end package management. Ensure Bower is installed globally before running this command. ```bash bower install require-css ``` -------------------------------- ### PHP: Get Event Sign-up List (Admin) Source: https://context7.com/wlight/zsff/llms.txt This snippet shows how an administrator can retrieve a paginated list of event sign-ups. It includes joining with 'user' and 'price' relations to display relevant user and pricing information for each sign-up. The results are ordered by sign-up time in descending order. Dependencies include the 'EventSignUp' model with its relationships. ```php // Get event sign-up list (admin) $signups = EventSignUp::with('user', 'price') ->where('activity_id', $event_id) ->where('paid', 1) ->order('add_time DESC') ->paginate(20); ``` -------------------------------- ### Install CSso for CSS Compression Source: https://github.com/wlight/zsff/blob/master/public/pc/plugins/require-css/README.md To enable CSS compression with csso, first install it globally using npm. The build log will then display the compression results. If the global module is not found when running r.js through NodeJS, install csso locally. ```bash npm install csso -g ``` -------------------------------- ### Basic Monolog Logging Example in PHP Source: https://github.com/wlight/zsff/blob/master/vendor/monolog/monolog/README.md This PHP code demonstrates the basic usage of Monolog. It creates a logger instance, configures a StreamHandler to write logs to a file named 'path/to/your.log' with a WARNING level or higher, and then adds warning and error records to the log channel. ```php <?php use Monolog\Logger; use Monolog\Handler\StreamHandler; // create a log channel $log = new Logger('name'); $log->pushHandler(new StreamHandler('path/to/your.log', Logger::WARNING)); // add records to the log $log->addWarning('Foo'); $log->addError('Bar'); ``` -------------------------------- ### Initialize Vue.js Application - Course Listing Source: https://github.com/wlight/zsff/blob/master/application/wap/view/first/special/special_cate.html Creates a Vue.js instance that manages course categorization, filtering, and pagination. The application initializes with methods to fetch category data, handle navigation scrolling, filter courses by grade and subject, and implement infinite scroll loading. It uses axios for API requests and custom helper utilities. ```javascript var cate_id = {$cate_id}; var subject_id = {$subject_id}; require(['vue', 'axios', 'helper', 'special-type'], function (Vue, axios, $h, specialType) { var vm = new Vue({ el: '#app', data: { gradeCate: [], subjectCate: [], specialList: [], gradeId: -1, subjectId: -1, search: '', loadTitle: '', page: 1, limit: 10, loading: false, loadend: false, count: 0 }, computed: { updateSpecialList: function () { return this.specialList.map(function (value) { value.special_type = specialType[value.type]; return value; }); } }, created: function () { this.getCateList(); }, mounted: function () { this.$nextTick(function () { $h.EventUtil.listenTouchDirection(document, function () { this.getSpecialList(); }.bind(this), false); }); } }); }); ``` -------------------------------- ### Get and Set Spreadsheet Creation Date/Time (PHP) Source: https://github.com/wlight/zsff/blob/master/vendor/phpoffice/phpspreadsheet/docs/references/features-cross-reference.md Shows how to get and set the creation date and time for a spreadsheet. This functionality is managed through the spreadsheet's properties object and dedicated methods. ```php $spreadsheet->getProperties()->getCreated() $spreadsheet->getProperties()->setCreated() ``` -------------------------------- ### Install ReactPHP STOMP Package Source: https://github.com/wlight/zsff/blob/master/vendor/workerman/workerman/README.md Composer command to install the React STOMP library for STOMP protocol communication. Required dependency for message broker integration with ReactPHP applications. ```bash composer require react/stomp ``` -------------------------------- ### Initiate WeChat Pay (JavaScript) Source: https://github.com/wlight/zsff/blob/master/application/wap/view/first/special/task_info.html Handles the initiation of WeChat payment using the `mapleWx` library. It requires `jssdk` configuration and provides success and failure callbacks. On successful payment, it calls `vm.successOrder`; on failure or cancellation, it calls `vm.extendOrder`. ```javascript wechatPay: function (config) { var vm = this; mapleWx($jssdk(), function () { this.chooseWXPay(config, function () { vm.successOrder(); }, { fail: vm.extendOrder, cancel: vm.extendOrder }); }); } ``` -------------------------------- ### Run a PhpSpreadsheet sample from CLI Source: https://github.com/wlight/zsff/blob/master/vendor/phpoffice/phpspreadsheet/docs/index.md This command executes a specific PhpSpreadsheet sample script directly from the command line. Replace the sample path with the desired script. ```sh php vendor/phpoffice/phpspreadsheet/samples/Basic/01_Simple.php ```