dg/twitter-php 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

dg/twitter-php

Composer 安装命令:

composer require dg/twitter-php

包简介

Small and easy library for X (formerly Twitter) API v2

README 文档

README

Downloads this Month Tests Latest Stable Version License

Small and easy-to-use library for the X (formerly Twitter) API v2.

Installation

Install via Composer:

composer require dg/twitter-php

Requirements: PHP 8.2 or higher.

Getting API Keys

  1. Go to X Developer Portal

  2. Sign in and create a Developer account (Free tier is sufficient)

  3. Create a new Project and App

  4. Set up permissions (important!):

    • App Settings → User authentication settings → Edit
    • App permissions: Read and Write
    • Type of App: Web App
    • Callback URI: https://localhost/callback (placeholder, not used)
    • Website URL: any valid URL
  5. Generate keys:

    • Keys and tokens → API Key and Secret → Generate
    • Keys and tokens → Access Token and Secret → Generate

    ⚠️ Note: After changing permissions, you must regenerate the Access Token!

  6. Use case description (required by X, min. 250 characters):

    I am building a personal tool for publishing my own content to X. The
    application will only be used to post text updates and images from my own
    account. It will not read, collect, or analyze any data from other users.
    There is no automation of likes, retweets, follows, or any other
    interactions. This is strictly a single-user tool for my personal use to
    streamline my social media posting workflow.
    

Usage

Create the client using your API credentials:

use DG\X\Client;

$x = new Client($consumerKey, $consumerSecret, $accessToken, $accessTokenSecret);

Note: The Free tier of the X API only allows sending and deleting tweets and reading your own profile (authenticate()). Reading timelines, searching, user info, followers and other read endpoints require the Basic tier or higher.

Sending Tweets

$x->sendTweet('I am fine today.');

With an image:

$x->sendTweet('Check this out!', '/path/to/image.jpg');

With multiple images:

$x->sendTweet('Photos!', ['/path/to/img1.jpg', '/path/to/img2.jpg']);

Timelines

Get your own tweets:

$tweets = $x->getMyTweets();

Get your home timeline (you and people you follow):

$tweets = $x->getTimeline();

Get your mentions:

$tweets = $x->getMentions();

Displaying Tweets

The static method Client::clickable() makes links, mentions and hashtags in tweets clickable:

foreach ($tweets as $tweet) {
	echo Client::clickable($tweet);
}

Searching

$results = $x->search('#php');

Users

$user = $x->getUser('elonmusk');
$user = $x->getUserById('44196397');
$followers = $x->getFollowers('44196397');

Social Actions

$x->follow('44196397');
$x->sendDirectMessage('44196397', 'Hello!');

Authentication

Test if user credentials are valid:

if (!$x->authenticate()) {
	die('Invalid credentials');
}

Custom API Requests

You can call any X API v2 endpoint directly:

$result = $x->request('tweets', 'POST', ['text' => 'Hello from raw API!']);
$result = $x->request('users/me', 'GET', ['user.fields' => 'description,profile_image_url']);

Error Handling

All methods throw DG\X\Exception on error:

try {
	$x->sendTweet('Hello!');
} catch (DG\X\Exception $e) {
	echo 'Error: ', $e->getMessage();
}

Backward Compatibility

The old class names DG\Twitter\Twitter, DG\Twitter\Exception, Twitter and TwitterException are available as aliases for DG\X\Client and DG\X\Exception.

Support Me

Buy me a coffee

Thank you!

Changelog

v5.0 (2/2026)

  • new namespace DG\X with Client class
  • uses X API v2 endpoints
  • uses Guzzle HTTP client (replaces raw CURL)
  • simplified inline OAuth 1.0a
  • clean API: sendTweet(), deleteTweet(), getTweet(), getMyTweets(), getTimeline(), getMentions(), search(), getUser(), getUserById(), getFollowers(), follow(), sendDirectMessage()
  • PHPStan level 8
  • Nette Tester tests
  • requires PHP 8.2+

v4.1 (11/2019)

  • added Delete Method (#68)
  • token is optional throughout + supply get() method

v4.0 (2/2019)

  • requires PHP 7.1 and uses its advantages like typehints, strict types etc.
  • class Twitter is now DG\Twitter\Twitter
  • class TwitterException is now DG\Twitter\Exception

v3.8 (2/2019)

  • Twitter::sendDirectMessage() uses new API
  • Twitter::clickable: added support for $status->full_text (#60)

v3.7 (3/2018)

  • minimal required PHP version changed to 5.4
  • Twitter::send() added $options
  • Twitter::clickable() now works only with statuses and entites
  • fixed coding style

v3.6 (8/2016)

  • added loadUserFollowersList() and sendDirectMessage()
  • Twitter::send() allows to upload multiple images
  • changed http:// to https://

v3.5 (12/2014)

  • allows to send message starting with @ and upload file at the same time in PHP >= 5.5

v3.4 (11/2014)

  • cache expiration can be specified as string
  • fixed some bugs

v3.3 (3/2014)

  • Twitter::send($status, $image) can upload image
  • added Twitter::follow()

v3.2 (1/2014)

  • Twitter API uses SSL OAuth
  • Twitter::clickable() supports media
  • added Twitter::loadUserInfoById() and loadUserFollowers()
  • fixed Twitter::destroy()

v3.1 (3/2013)

  • Twitter::load() - added third argument $data
  • Twitter::clickable() uses entities; pass as parameter status object, not just text
  • added Twitter::$httpOptions for custom cURL configuration

v3.0 (12/2012)

  • updated to Twitter API 1.1

v2.0 (8/2012)

  • added support for OAuth authentication protocol
  • added Twitter::clickable() which makes links, @usernames and #hashtags clickable
  • installable via composer require dg/twitter-php

v1.0 (7/2008)

  • initial release

(c) David Grudl, 2008, 2026 (https://davidgrudl.com)

dg/twitter-php 适用场景与选型建议

dg/twitter-php 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 522.2k 次下载、GitHub Stars 达 536, 最近一次更新时间为 2012 年 08 月 31 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「api」 「oauth」 「twitter」 「x」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 dg/twitter-php 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 dg/twitter-php 我们能提供哪些服务?
定制开发 / 二次开发

基于 dg/twitter-php 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 522.2k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 537
  • 点击次数: 35
  • 依赖项目数: 14
  • 推荐数: 0

GitHub 信息

  • Stars: 536
  • Watchers: 55
  • Forks: 146
  • 开发语言: PHP

其他信息

  • 授权协议: BSD-3-Clause
  • 更新时间: 2012-08-31