uncgits/canvas-api-wrapper-laravel

Laravel Wrapper for Canvas API PHP Library

1.0.2 2020-08-19 21:28 UTC

This package is auto-updated.

Last update: 2024-04-20 03:33:15 UTC


README

This package is a Laravel wrapper for the UNCG Canvas API PHP Library package, so that the Canvas API PHP Library can be used in Laravel apps.

Installation

  1. composer require uncgits/canvas-api-wrapper-laravel
  2. IF running Laravel 5.4 or below: Add Uncgits\CanvasApiLaravel\ServiceProvider::class, to your config/app.php file
  3. Run php artisan vendor:publish --provider='Uncgits\CanvasApiLaravel\ServiceProvider' - to publish the canvas-api.php config file
  4. Set your environment credentials in your .env file, and set your configuration options in config/canvas-api.php

Dependencies

This package has dependencies on uncgits/canvas-api-php-library and standaniels/flash

Quick Start

Config and .env setup

You'll want to fill in details on your environment(s) in the published canvas-api.php file. The idea here is that you will potentially have multiple sets of credentials to be used, since Canvas offers each client a production, beta, and test instance. You should take a look at the default placeholders in the config file and replace mydomain with your Canvas domain (e.g. 'myschool' for 'myschool.instructure.com'). In addition, you'll want to modify the references to the .env variables to something that makes sense. Example:

// config/canvas-api.php

'configs' => [
    'myschool' => [
        'production' => [
            'class' => \App\CanvasApiConfigs\Myschool\Production::class,
            'host'  => env('CANVAS_API_MYSCHOOL_PRODUCTION_HOST'),
            'token' => env('CANVAS_API_MYSCHOOL_PRODUCTION_TOKEN'),
            'proxy' => [
                'use'  => env('CANVAS_API_MYSCHOOL_PRODUCTION_USE_HTTP_PROXY', 'false') == 'true',
                'host' => env('CANVAS_API_MYSCHOOL_PRODUCTION_HTTP_PROXY_HOST'),
                'port' => env('CANVAS_API_MYSCHOOL_PRODUCTION_HTTP_PROXY_PORT'),
            ],
        ],
    ]
]

Set up Config class(es)

In accordance with the documentation on the uncgits/canvas-api-php-library package, set up a Config class for each set of Canvas credentials you wish to use with this package. A recommended namespacing would be App\CanvasApiConfigs. In here you'll most likely hook back into your canvas-api.php config file using the config() directive. Example:

// app/CanvasApiConfigs/Myschool/Production.php

<?php

namespace App\CanvasApiConfigs\Myschool;

use Uncgits\CanvasApi\CanvasApiConfig;

class Production extends CanvasApiConfig
{
    public function __construct()
    {
        $this->setApiHost(config('canvas-api.configs.myschool.production.host'));
        $this->setToken(config('canvas-api.configs.myschool.production.token'));

        if (config('canvas-api.configs.myschool.production.proxy.use', false)) {
            $this->setUseProxy(true);
            $this->setProxyHost(config('canvas-api.configs.myschool.production.proxy.host'));
            $this->setProxyPort(config('canvas-api.configs.myschool.production.proxy.port'));
        }
    }
}

.env variables

At minimum, you should add the host and token information for the environment(s) you plan to use with this library.

Note: do not use protocols (http:// or https://) in your host information

CANVAS_API_MYDOMAIN_PRODUCTION_HOST=
CANVAS_API_MYDOMAIN_PRODUCTION_TOKEN=

Set default Client and Adapter

In the canvas-api.php config file, fill in both of the items under defaults. defaults.config should be another config key for that same file that points to the entry in configs that you want to use. defaults.adapter should point to whichever Adapter class you want to use (either ::class syntax or the full name as a string will be fine there).

Once you finish this step you should be ready to make your Canvas API calls!

Usage

Before proceeding here, please ensure you've read and are familiar with the details of the uncgits/canvas-api-php-library package.

Use the facade

The recommended usage for this wrapper package involves the CanvasApi root-level facade. Note that this requires you to set the Client you're using (e.g. Accounts, Users, etc.) on each call, however:

$result = \CanvasApi::using('accounts')->listAccounts();

Instantiate the CanvasApi class itself

If you prefer, you can instantiate the Uncgits\CanvasApiLaravel\CanvasApi class and set a Client class on that instance instead, for better permanence:

$api = new Uncgits\CanvasApiLaravel\CanvasApi; // Config and Adapter classes are pulled in based on defaults in the config file
$api->setClient(new Uncgits\CanvasApi\Clients\Accounts); // this is not discernable via a default setting, so it must be set.

$result = $api->listAccounts();

Configuration options

Logging

If you wish to implement logging or flash messages or anything of the sort, it is recommended to create a listener that hooks into the ApiRequestFinished event, and perform your logic for logging / messages / etc. from there.

Caching

For speed, adherence to rate limits, and overall performance, caching is built into this library. This utilizes the Laravel Cache mechanism (which, like Logs, can be set however you want in the Laravel config). You can optionally disable this by adding CANVAS_API_CACHING=off in your .env file.

Cache TTL

The TTL of the cache is set to 10 minutes by default, but by adding CANVAS_API_CACHE_MINUTES=x to your .env file, you can set the cache to expire after x minutes instead.

Cached clients / methods

Caching is performed only for specified clients/methods, and is only active for GET requests (obviously, you would not want to cache requests that are designed to actually modify information in Canvas, like POST or PUT or DELETE requests).

To specify which Clients should be cached, utilize the cacheable_calls array in the canvas-api.php config file:

'cacheable_calls' => [
    // use the Client as the key for an array entry
    'Uncgits\CanvasApi\Clients\Accounts' => [
        // list each method name you wish to cache here. aliases need to be listed separately!
        'listAccounts',
        'getSingleAccount',
        'getAccount', // an alias for getSingleAccount - needs to be listed here as well
    ],

    // to cache all GET transactions made with a client, just use an asterisk instead
    'Uncgits\CanvasApi\Clients\Users' => ['*']
],

Determining whether the cache was used

The CanvasApi class in this package will return a CanvasApiResult class that is an extension of the original, adding two properties: $source and $cacheKey. You can access either of these on the object using standard getters getSource() and getCacheKey().

Bypassing the cache

On an individual API call, you can chain withoutCache() to bypass the cache on that individual transaction, regardless of what the overall settings are in the application.

Events

When an API transaction is initiated, the ApiRequestStarted event will be dispatched. Similarly, as the result is returned, the ApiRequestFinished event will be dispatched. Nothing is set by default to listen to these events, but you can hook into them as needed in your application.

As recommended above, listeners would be a great place to implement logging or other recording of API requests / results in your application.

Validation Rules

Some validation rules are provided by default as an example of some of the things you could add to your forms. Feel free to extend these or write your own; pull requests for additional rules would be welcome!

Contributing

Please feel free to submit a pull request to this package to help improve it or fix issues.

License

See the LICENSE file for license rights and limitations (BSD).

Questions? Concerns?

Please use the Issue Tracker on this repository for reporting bugs. For security-related concerns, please contact its-laravel-devs-l@uncg.edu directly instead of using the Issue Tracker.

Version History

1.0.2

  • Readme updates for clarity

1.0.1

  • Adds BSD license info to composer.json

1.0

  • Official open source licensing

0.2.5

  • fix for name of file for AllUsersExistInCanvas rule

0.2.4

  • Adds ability to specify which kind of login ID to use in UserExistsInCanvas rule
  • More explicit failure message in UserExistsInCanvas rule

0.2.3

  • Fix for UserExistsInCanvas rule to explicitly use Users client.

0.2.2

  • change to PSR-4 declaration since we were already following it

0.2.1

  • Fix for making an API call when caching is on

0.2

  • Adds support for maximum results (capping resultset size)

0.1.2

  • Require numbered version of canvas-api-php-library - currently 0.5

0.1.1

  • Fix a bug in caching that would not pass the unserialized result properly to the Event class, resulting in a PHP warning

0.1

  • Initial release.