Parse PHP SDK

repository·master·Indexed 21 days ago

https://github.com/parse-community/parse-php-sdk

A PHP library for interacting with a Parse Server backend. It provides tools for data management via Parse Objects, user authentication, Access Control Lists (ACLs), aggregate queries, cloud function and job execution, file management, push notifications, server schema control, and server log retrieval. Supports both Curl and Stream HTTP clients.

Tokens
17.2K
Snippets
79
Records
89
Agent score
71%

What's inside parse-php-sdk

  1. Import Parse SDK classes

    master

    To use the Parse PHP SDK, you must include the appropriate use declarations for the classes you intend to utilize in your PHP files.

    use Parse\ParseObject;
    use Parse\ParseQuery;
    use Parse\ParseACL;
    use Parse\ParsePush;
    use Parse\ParseUser;
    use Parse\ParseInstallation;
    use Parse\ParseException;
    use Parse\ParseAnalytics;
    use Parse\ParseFile;
    use Parse\ParseCloud;
    use Parse\ParseClient;
    use Parse\ParsePushStatus;
    use Parse\ParseServerInfo;
    use Parse\ParseLogs;
    use Parse\ParseAudience;
  2. Initialize the ParseClient

    master

    After including the SDK files, initialize the ParseClient using your Parse API keys. You must provide the app_id and master_key. The rest_key is optional; if your server does not require it, you can pass null.

    // Standard initialization
    ParseClient::initialize( $app_id, $rest_key, $master_key );
    
    // Initialization without a REST key
    ParseClient::initialize( $app_id, null, $master_key );
  3. Verify Server Connectivity with a Health Check

    master

    Use ParseClient::getServerHealth() to verify that your setServerURL configuration (URL and mount path) is correct.

    The method returns an array containing a status (the HTTP response code) and a response. The response contains the server's reply and may be a JSON array or a string if the response cannot be decoded.

    $health = ParseClient::getServerHealth();
    if($health['status'] === 200) {
        // everything looks good!
    }
  4. Install the Parse PHP SDK via Composer

    master

    To install the SDK using Composer, create a composer.json file in your project's root directory with the following requirement:

    {
        "require": {
            "parse/php-sdk" : "1.5.*"
        }
    }

    Then, run composer install to download the SDK and set up the autoloader. Finally, include the autoloader in your PHP script:

    require 'vendor/autoload.php';
  5. Configure the Server URL and Mount Point

    master

    Set the remote URL and the route prefix (mount point) for your Parse Server using ParseClient::setServerURL().

    Note: Parse Server's default port is 1337. The second parameter is the route prefix (e.g., parse).

    Example: If your server is at http://example.com:1337/parse, use:

    ParseClient::setServerURL('http://example.com:1337', 'parse');
    ParseClient::setServerURL('https://my-parse-server.com:port', 'parse');
  6. Register and use ParseObject subclasses

    master

    To use typed subclasses instead of generic ParseObject instances, you must register your subclasses. This allows the SDK to map Parse classes to specific PHP classes and enables typed queries.

    Workflow:

    1. Define a class that extends ParseObject and defines a $parseClassName property.
    2. Call YourSubclass::registerSubclass() before performing any other Parse operations.
    3. Use YourSubclass::query() to create a ParseQuery specifically for that subclass.

    Methods:

    • registerSubclass(): Registers the called class as the handler for its $parseClassName.
    • hasRegisteredSubclass($parseClassName): Checks if a subclass is registered for a given class name.
    • getRegisteredSubclass($parseClassName): Returns the registered subclass or a generic ParseObject if none is found.
    • query(): Creates a ParseQuery instance for the registered subclass.
    class MyTask extends ParseObject {
        public static $parseClassName = 'Task';
    }
    
    // Must be called early
    MyTask::registerSubclass();
    
    // Now you can create typed queries
    $query = MyTask::query();
  7. Manage user authentication with ParseUser

    master

    The ParseUser class provides methods for user lifecycle management, including signing up, logging in, and logging out. Authentication is tracked via a sessionToken.

    // Sign up a new user
    $user = new Parse\ParseUser();
    $user->setUsername('new_user');
    $user->setPassword('secure_password');
    $user->setEmail('user@example.com');
    $user->signUp();
    
    // Log in an existing user
    $user = Parse\ParseUser::logIn('username', 'password');
    
    // Log out
    Parse\ParseUser::logOut();
  8. Manage object permissions with ParseACL

    master

    The ParseACL class is used to control which users, roles, or the public can access or modify a specific ParseObject. You can grant read and write permissions separately. Permissions can be assigned to:

    • Specific users (via ParseUser object or user ID string).
    • Roles (via ParseRole object or role name string).
    • The public (using the * key).

    Note that checking getReadAccess or getWriteAccess for a specific user only returns whether they are explicitly allowed. A user might still have access if the public has access or if they belong to a role that has access.

    // Example of creating an ACL and setting permissions
    $acl = new Parse\ParseACL();
    
    // Grant public read access
    $acl->setPublicReadAccess(true);
    
    // Grant a specific user read and write access
    $acl->setUserReadAccess($user, true);
    $acl->setUserWriteAccess($user, true);
    
    // Grant a role read access
    $acl->setRoleReadAccessWithName('Admin', true);
  9. Manage many-to-many relationships with ParseRelation

    master

    The ParseRelation class is used to manage many-to-many relationships in Parse. It allows you to add or remove ParseObject instances from a specific relation key on a parent object. Each relation is tied to a parent ParseObject, a specific key, and a target className representing the objects being related.

    // Assuming $parent is a ParseObject and 'tags' is the relation key
    $relation = new Parse\ParseRelation($parent, 'tags', 'TagClass');
    
    // Add a single object or an array of objects
    $relation->add($tagObject);
    $relation->add([$tag1, $tag2]);
    
    // Remove objects from the relation
    $relation->remove($tagObject);
  10. Manage Parse Schemas with ParseSchema

    master

    The ParseSchema class is used to manage collection schemas (classes) on your Parse server. It allows you to create, retrieve, update, and delete schemas, as well as manage fields and indexes.

    Important: All schema methods require the use of your application's master key.

    To use ParseSchema, you must instantiate it with a className representing the data class you wish to manage.

    use Parse\ParseSchema;
    
    $schema = new ParseSchema('MyClassName');
  11. Build and execute queries with ParseQuery

    master

    The ParseQuery class is used to build constraints and execute queries against a specific Parse Class. You initialize it by passing the class name to the constructor. Most constraint methods (like equalTo, greaterThan, etc.) return the ParseQuery instance, allowing you to chain calls to build complex queries.

    $query = new Parse\ParseQuery('GameScore');
    $query->equalTo('score', 100)
          ->greaterThan('level', 5);
    
    $results = $query->find();