Search code examples
phpthrift

PHP: resolving types in different files/namespaces


I am trying to write a PHP client for a Thrift server written in C. I am following the tutorial given at http://chanian.com/2010/05/13/thrift-tutorial-a-php-client/.

I am very new to PHP and, I suspect, am missing some of the language fundamentals.

The code in question is:

<?php 
// Setup the path to the thrift library folder
$GLOBALS['THRIFT_ROOT'] = 'Thrift';

// Load up all the thrift stuff
require_once $GLOBALS['THRIFT_ROOT'].'/Thrift.php';
require_once $GLOBALS['THRIFT_ROOT'].'/protocol/TBinaryProtocol.php';
require_once $GLOBALS['THRIFT_ROOT'].'/transport/TSocket.php';
require_once $GLOBALS['THRIFT_ROOT'].'/transport/TBufferedTransport.php';

// Load the package that we autogenerated for this tutorial
require_once $GLOBALS['THRIFT_ROOT'].'/packages/encabulationgame/EncabulationGame.php';

// Several things might go wrong
try {
    // Create a thrift connection (Boiler plate)
    $socket = new TSocket('localhost', '65123'); <--error is here

I am getting an error "Class 'TSocket' not found in /var/www/foo/scores.php on line 22"

TSocket is defined in Thrift/transport/TSocket.php. The Thrift/transport/TSocket.php file (with comments removed) reads:

<?php

namespace Thrift\Transport;

use Thrift\Transport\TTransport;
use Thrift\Exception\TException;
use Thrift\Exception\TTransportException;
use Thrift\Factory\TStringFuncFactory;

/**
 * Sockets implementation of the TTransport interface.
 *
 * @package thrift.transport
 */
class TSocket extends TTransport {

If I change my code to:

 $socket = new Thrift\Transport\TSocket('localhost', '65123');

Then my code (well, this line, at least) no longer throws an error. I'm curious: what did the author of this tutorial do to get this code to work on his system that I'm not doing on my system?

Secondly, I attempted to solve the problem by adding the line:

use Thrift\Transport;

to my file before I create $socket, but that didn't solve the problem as I'd expected it to.

How do I convince PHP to resolve this type that's defined in another file? (There are several types in several files that I have to resolve.)


Solution

  • PHP does not import an entire namespace, instead you must "use" each namespaced class you wish to import. Instead of use Thrift\Transport; write

    use Thrift\Transport\TSocket;
    

    This is described in more detail in the manual under Using Namespaces: Aliasing/Importing. Is it possible that the article was written before Thrift was namespaced?