xchimx/laravel-unsplash

Laravel 包,用于轻松集成 Unsplash API。它允许你在 Laravel 应用程序中使用 Unsplash API 来获取照片、集合和用户数据。

1.0.0 2024-10-01 16:03 UTC

This package is auto-updated.

Last update: 2024-10-01 16:04:43 UTC


README

A Laravel package for easy integration with the Unsplash API. It allows you to use the Unsplash API in your Laravel applications to fetch photos, collections, and user data.

---

安装

您可以通过 composer 安装此包

composer require xchimx/laravel-unsplash

使用 artisan CLI 工具发布配置文件

php artisan vendor:publish --provider="Xchimx\UnsplashApi\UnsplashServiceProvider" --tag="config"

最后,在您的 ENV 文件中设置 API 密钥

UNSPLASH_ACCESS_KEY=your_unsplash_access_key

ENV 文件中的可选速率限制设置

UNSPLASH_RATE_LIMITING_ENABLED=true
UNSPLASH_RATE_LIMITING_THRESHOLD=10

使用

基本使用

您可以通过依赖注入将 UnsplashService 注入到控制器中

use Xchimx\UnsplashApi\UnsplashService;

class UnsplashController extends Controller
{
    protected $unsplashService;

    public function __construct(UnsplashService $unsplashService)
    {
        $this->unsplashService = $unsplashService;
    }

    public function search()
    {
        $photos = $this->unsplashService->searchPhotos('Nature');

        return view('unsplash.search', compact('photos'));
    }
}

使用外观

或者,您可以使用提供的 Unsplash 外观

use Xchimx\UnsplashApi\Facades\Unsplash;

class UnsplashController extends Controller
{
    public function search()
    {
        $photos = Unsplash::searchPhotos('Nature');

        return view('unsplash.search', compact('photos'));
    }
}

UnsplashService 方法

UnsplashService 提供以下方法

  1. searchPhotos($query, $perPage = 10, $page = 1)
  2. searchPhotosAdvanced(array $params)
  3. getPhoto($id)
  4. getRandomPhoto(array $params = [])
  5. getPhotoDownloadLink($id)
  6. listCollections($perPage = 10, $page = 1)
  7. getCollection($id)
  8. getUser($username)
  9. getUserPhotos($username, $perPage = 10, $page = 1)
  10. searchCollections($query, $perPage = 10, $page = 1)
  11. withOptions(array $options)

控制器示例

以下是一些控制器示例,展示了如何在 Laravel 控制器中使用 UnsplashService 的各种方法。

1. searchPhotos

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Xchimx\UnsplashApi\Facades\Unsplash;

class UnsplashController extends Controller
{
    public function search(Request $request)
    {
        $query = $request->input('query', 'Nature');
        $photos = Unsplash::searchPhotos($query);

        return view('unsplash.search', compact('photos', 'query'));
    }
}

Blade 视图

@extends('layouts.app')

@section('content')
<h1>Photo by {{ $photo['user']['name'] }}</h1>
<img src="{{ $photo['urls']['regular'] }}" alt="{{ $photo['alt_description'] }}">
<p>{{ $photo['description'] ?? 'No description available.' }}</p>
@endsection

2. searchPhotosAdvanced

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Xchimx\UnsplashApi\Facades\Unsplash;

class UnsplashController extends Controller
{
    public function advancedSearch(Request $request)
    {
        $params = [
            'query' => $request->input('query', 'Nature'),
            'color' => $request->input('color'),
            'orientation' => $request->input('orientation'),
            'per_page' => $request->input('per_page', 15),
            'page' => $request->input('page', 1),
        ];

        $params = array_filter($params);

        $response = Unsplash::searchPhotosAdvanced($params);

        $photos = $response['results'];

        return view('unsplash.advanced_search', compact('photos', 'params'));
    }
}

3. getPhoto

namespace App\Http\Controllers;

use Xchimx\UnsplashApi\Facades\Unsplash;

class UnsplashController extends Controller
{
    public function show($id)
    {
        $photo = Unsplash::getPhoto($id);

        return view('unsplash.show', compact('photo'));
    }
}

Blade 视图

@extends('layouts.app')

@section('content')
<h1>Photo by {{ $photo['user']['name'] }}</h1>
<img src="{{ $photo['urls']['regular'] }}" alt="{{ $photo['alt_description'] }}">
<p>{{ $photo['description'] ?? 'No description available.' }}</p>
@endsection

4. getRandomPhoto

namespace App\Http\Controllers;

use Xchimx\UnsplashApi\Facades\Unsplash;

class RandomPhotoController extends Controller
{
    public function show()
    {
        $photo = Unsplash::getRandomPhoto();

        return view('photos.random', compact('photo'));
    }
}

Blade 视图

@extends('layouts.app')

@section('content')
<h1>Random Photo</h1>
<img src="{{ $photo['urls']['regular'] }}" alt="{{ $photo['alt_description'] }}">
<p>Photo by {{ $photo['user']['name'] }}</p>
@endsection

5. getPhotoDownloadLink

namespace App\Http\Controllers;

use Xchimx\UnsplashApi\Facades\Unsplash;

class UnsplashController extends Controller
{
    public function download($id)
    {
        $downloadUrl = Unsplash::getPhotoDownloadLink($id);

        return redirect($downloadUrl);
    }
}

6. listCollections

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Xchimx\UnsplashApi\Facades\Unsplash;

class CollectionController extends Controller
{
    public function index(Request $request)
    {
        $page = $request->input('page', 1);
        $collections = Unsplash::listCollections(15, $page);

        return view('collections.index', compact('collections'));
    }
}

Blade 视图

@extends('layouts.app')

@section('content')
<h1>Collections</h1>
@foreach ($collections as $collection)
<div>
    <h2>{{ $collection['title'] }}</h2>
    <p>{{ $collection['description'] ?? 'No description' }}</p>
    <a href="{{ route('collections.show', $collection['id']) }}">View Details</a>
</div>
@endforeach
@endsection


7. getCollection

namespace App\Http\Controllers;

use Xchimx\UnsplashApi\Facades\Unsplash;

class CollectionController extends Controller
{
    public function show($id)
    {
        $collection = Unsplash::getCollection($id);

        return view('collections.show', compact('collection'));
    }
}

Blade 视图

@extends('layouts.app')

@section('content')
<h1>{{ $collection['title'] }}</h1>
<p>{{ $collection['description'] ?? 'No description available.' }}</p>
<!-- Display additional details -->
@endsection

8. getUser

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Xchimx\UnsplashApi\Facades\Unsplash;

class UserController extends Controller
{
    public function user($username, Request $request)
    {
        $user  = Unsplash::getUser($name);

        return view('user', compact('user'));
    }
}

9. getUserPhotos

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Xchimx\UnsplashApi\Facades\Unsplash;

class UserController extends Controller
{
    public function photos($username, Request $request)
    {
        $page = $request->input('page', 1);
        $photos = Unsplash::getUserPhotos($username, 15, $page);

        return view('users.photos', compact('photos', 'username'));
    }
}

Blade 视图

@extends('layouts.app')

@section('content')
<h1>Photos by {{ $username }}</h1>
@foreach ($photos as $photo)
<div>
    <img src="{{ $photo['urls']['small'] }}" alt="{{ $photo['alt_description'] }}">
    <p>{{ $photo['description'] ?? 'No description' }}</p>
</div>
@endforeach
@endsection

10. searchCollections

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Xchimx\UnsplashApi\Facades\Unsplash;

class CollectionController extends Controller
{
    public function search(Request $request)
    {
        $query = $request->input('query', 'Nature');
        $page = $request->input('page', 1);

        $collections = Unsplash::searchCollections($query, 15, $page);

        return view('collections.search', compact('collections', 'query'));
    }
}

Blade 视图

@extends('layouts.app')

@section('content')
<h1>Search Results for Collections: "{{ $query }}"</h1>
@foreach ($collections['results'] as $collection)
<div>
    <h2>{{ $collection['title'] }}</h2>
    <p>{{ $collection['description'] ?? 'No description' }}</p>
    <a href="{{ route('collections.photos', $collection['id']) }}">View Photos</a>
    @endforeach
@endsection
</div>

11. withOptions

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Xchimx\UnsplashApi\Facades\Unsplash;

class CollectionController extends Controller
{
    public function searchWithTimeout(Request $request)
    {
        // Use withOptions to set custom Guzzle options, e.g., timeout
        $photos = Unsplash::withOptions(['timeout' => 2])->searchPhotos('Nature');

        return view('unsplash.search', compact('photos'));
    }
}

Blade 视图

@extends('layouts.app')

@section('content')
<h1>Search Results for Collections: "{{ $query }}"</h1>
@foreach ($collections['results'] as $collection)
<div>
    <h2>{{ $collection['title'] }}</h2>
    <p>{{ $collection['description'] ?? 'No description' }}</p>
    <a href="{{ route('collections.photos', $collection['id']) }}">View Photos</a>
    @endforeach
@endsection
</div>

速率限制中间件

此包包含用于监控和处理 Unsplash API 速率限制的中间件。中间件默认启用,可以在配置选项中进行自定义。

配置

速率限制设置位于 config/unsplash.php

'rate_limiting' => [
    'enabled' => env('UNSPLASH_RATE_LIMITING_ENABLED', true),
    'threshold' => env('UNSPLASH_RATE_LIMITING_THRESHOLD', 10),
],
  • enabled: 启用或禁用速率限制中间件。
  • threshold: 中间件介入的剩余请求数阈值。

使用

要在您的路由中使用中间件,请按以下方式添加

Route::middleware(['unsplash.rate_limit'])->group(function () {
    Route::get('/unsplash/search', [UnsplashController::class, 'search'])->name('unsplash.search');
    // Other routes...
});

错误处理

在 API 调用过程中处理错误非常重要,尤其是在与外部服务通信时。

public function search(Request $request)
{
    try {
        $photos = Unsplash::searchPhotos('Nature');
    } catch (\Exception $e) {
        // Log the error or display a user-friendly message
        return back()->withErrors('There was a problem communicating with the Unsplash API.');
    }

    return view('unsplash.search', compact('photos'));
}

关于 Unsplash API 的注意事项

  • 速率限制:Unsplash API 有速率限制。请确保监控请求数量并使用提供的中间件。
  • 归属:在使用照片时,必须根据 Unsplash 的指南给摄影师署名。
  • API 文档:有关更多详细信息,请参阅 Unsplash API 文档。

许可证

此软件包根据 MIT 许可证发布。