+ Reply to Thread
Results 1 to 1 of 1
This is a discussion on Salesforce Connect Class within the Salesforce PHP Tutorials forums, part of the Salesforce category; Connection class for Saleforce. Requirements: PHP >= 5.1.x Salesforce Toolkit for PHP
  1. #1
    SoN9ne is offline Junior Member
    Join Date
    Mar 2011
    Location
    Florida
    Posts
    1

    Salesforce Connect Class

    Connection class for Saleforce.

    Requirements:
    PHP >= 5.1.x
    Salesforce Toolkit for PHP >=5.1.x

    Folder structure (To be used as an example, you can have your own structure but make sure you update the SF_SOAPCLIENT_DIR and the index require_once):
    • public_html
      • sf-lib
        • toolkit (Salesforce Toolkit Folder)
        • SF_Connect.class.php
      • index.php
    SF_Connect.class.php
    PHP Code:
    <?php
    /**
     * Salesforce Connection
     *
     * Creates a connection to Salesforce
     * 
     * @author Jeremy Simkins
     * @version 0.0.1
     */
    class SF_Connect {
        
    /**
         * Instance of Saleforce Soap Client
         * @var resource
         */
        
    private static $soapClient;

        
    /**
         * WSDL Method
         * @var string
         */
        
    private static $wsdlMethod;

        
    /**
         * Salesforce User Login
         * @var string
         */
        
    const SALESFORCE_USER '**LOGIN**';

        
    /**
         * Salesforce User Login Password
         * @var string
         */
        
    const SALESFORCE_PASS '**PASS**';

        
    /**
         * Salesforce Token
         * @var string
         */
        
    const SALESFORCE_TOKEN '**TOKEN**';

        
    /**
         * Debug Mode
         * - True - Shows errors
         * - False - Emails errors
         *
         * SHOULD BE FALSE IN A LIVE ENVIRONMENT
         * @var bool
         */
        
    const IN_DEBUG_MODE true;

        
    /**
         * Email to send errors to
         * @var STRING
         */
        
    const ERROR_EMAIL '**EMAIL**';

        
    /**
         * Path to toolkit soapclient folder
         * @var string
         */
        
    const SF_SOAPCLIENT_DIR 'sf-lib/toolkit/soapclient/';

        
    /**
         * Initiates the Salesforce Connection
         * @param string $wsdlMethod
         */
        
    public static function connect($wsdlMethod 'partner') {
            
    # Prevent Stupid
            
    if (self::$soapClient) return;

            
    # Ensure we have a valid method
            
    if ( !$wsdlMethod || !in_array($wsdlMethod, array('partner''enterprise''metadata')) ) {
                die(((
    self::IN_DEBUG_MODE) ? 'Bad wsdl requested' 'Unable to connect to salesforce.com'));
            }

            try {
                
    # Create client and connection
                
    self::$soapClient self::getSoapClient($wsdlMethod);
                
    self::$soapClient->createConnection(self::SF_SOAPCLIENT_DIR self::$wsdlMethod '.wsdl.xml');

                
    # Login
                
    $tmpLogin self::$soapClient->login(self::SALESFORCE_USERself::SALESFORCE_PASS self::SALESFORCE_TOKEN);

                
    # Ensure password is still valid
                
    if ( $tmpLogin->passwordExpired ) {
                    if (
    self::IN_DEBUG_MODE) {
                        die(
    'Password has expired');
                    }
                    return 
    false;
                }
                return 
    true;
            } catch ( 
    SoapFault $e ) {
                
    $errorMessage "Error: [{$e->getCode()}{$e->getMessage()}";
                
    $errorMessage .= '<br />';
                
    $errorMessage .= "File:{$e->getFile()}<br />Line: {$e->getLine()}";
                
    $errorMessage .= '<br />';
                
    $errorMessage .= '<pre>' print_r($e->getTrace(), true) . '</pre>';

                
    # While in debug we can display the error
                
    if ( self::IN_DEBUG_MODE ) {
                    echo 
    $errorMessage;
                } else {
                    
    // To send HTML mail, the Content-type header must be set
                    
    $headers 'MIME-Version: 1.0' "\r\n";
                    
    $headers .= 'Content-type: text/html; charset=iso-8859-1' "\r\n";

                    
    mail(self::ERROR_EMAIL'Salesforce Error!'$errorMessage$headers);
                }
                return 
    false;
            }
        }

        
    /**
         * Returns proper resource for given wdsl Method
         * Also sets self::$wsdlMethod to ensure the proper soap client is initiated
         * @param string $wsdlMethod
         */
        
    private static function getSoapClient($wsdlMethod) {
            switch (
    strtolower($wsdlMethod)) {
                case 
    'enterprise':
                    
    # Require Client
                    
    require_once (self::SF_SOAPCLIENT_DIR 'SforceEnterpriseClient.php');
                    
    # Set method
                    
    self::$wsdlMethod 'enterprise';
                    
    # Return object
                    
    return new SforceEnterpriseClient();
                    break;
                case 
    'metadata':
                    
    # Require Client
                    
    require_once (self::SF_SOAPCLIENT_DIR 'SforceMetadataClient.php');
                    
    # Set method
                    
    self::$wsdlMethod 'metadata';
                    
    # Return object
                    
    return new SforceMetadataClient();
                    break;
                case 
    'partner':
                    
    # Require Client
                    
    require_once (self::SF_SOAPCLIENT_DIR 'SforcePartnerClient.php');
                    
    # Set method
                    
    self::$wsdlMethod 'partner';
                    
    # Return object
                    
    return new SforcePartnerClient();
                    break;
                default:
                    die(((
    self::IN_DEBUG_MODE) ? 'Bad client requested' 'Unable to connect to salesforce.com'));
                    break;
            }
        }

        
    /**
         * Logout current connection
         */
        
    public static function logout() {
            
    self::$soapClient->logout();
        }

        
    /**
         * Return soap client
         */
        
    public static function getClient() {
            return 
    self::$soapClient;
        }
    }

    /**
     * This clears out your local PHP WSDL cache incase you may have been performing
     * tests against your development account or Sandbox account
     */
    ini_set("soap.wsdl_cache_enabled""0");
    Test Script
    index.php
    PHP Code:
    # Require the connection class
    require_once 'sf-lib/SF_Connect.class.php';

    # Initialize the connection
    if ( !SF_Connect::connect() ) {
        
    # Connection failed, output error
        
    die('Unable to connect to salesforce.com');
    }

    /**
     * Successful connection
     *
     * Process actions here
     */

    # Demo
    $query "SELECT Id, FirstName, LastName from Lead";
    $queryResult SF_Connect::getClient()->query($query);
    $records $queryResult->records;
    foreach (
    $records as $sObject) {
        echo 
    "Id = ".$sObject->Id;
        echo 
    '<br />';
        echo 
    "First Name = ".$sObject->fields->FirstName;
        echo 
    '<br />';
        echo 
    "Last Name = ".$sObject->fields->LastName;
        echo 
    '<hr />';
    }

    # Don't forget to logout
    SF_Connect::logout(); 
    Defaults to partner as the default connection client.
    Below are examples on how to connect to Enterprise and Metadata:
    Enterprise Connection
    PHP Code:
    # Initialize the connection
    if ( !SF_Connect::connect('enterprise') ) {
        
    # Connection failed, output error
        
    die('Unable to connect to salesforce.com');

    Metadata connection
    PHP Code:
    # Initialize the connection
    if ( !SF_Connect::connect('metadata') ) {
        
    # Connection failed, output error
        
    die('Unable to connect to salesforce.com');

    I am working on my own library for Saleforce and plan to release more in the future.
    If you have any concerns, suggestions, or updates for the connection class, please let me know.

    Thanks to this post by saariko for a reference.

    Hope some find this useful
    Last edited by SoN9ne; 03-30-2011 at 10:34 AM. Reason: Added reference post and other connection method examples

+ Reply to Thread

Similar Threads

  1. Soapfault exception: [HTTP] could not connect to host in sforcebaseclient.php
    By drschultz in forum Salesforce Coding Discussions
    Replies: 2
    Last Post: 12-20-2010, 05:42 PM
  2. Fatal error: Class 'QueryResult'
    By sager@cmc.ca in forum Salesforce Coding Discussions
    Replies: 3
    Last Post: 02-08-2010, 10:40 AM
  3. sObject class?
    By eventhough in forum Salesforce Coding Discussions
    Replies: 2
    Last Post: 02-25-2009, 07:07 PM
  4. PHP Ajax class review for Open Technology Group
    By mike in forum Salesforce PHP Tutorials
    Replies: 2
    Last Post: 03-01-2008, 05:10 PM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

SEO by vBSEO 3.5.2