次の方法で共有


Microsoft Graph を使用して PHP アプリのユーザーを一覧表示する

この記事では、「Microsoft Graph を使用して PHP アプリをビルドする」で作成したアプリケーション と、Microsoft Graph ユーザー API を使用したアプリ専用認証を拡張します。 Microsoft Graph を使用して、organization内のユーザーを一覧表示します。

  1. GraphHelper クラスに以下のコードを追加します。

    public static function getUsers(): Models\UserCollectionResponse {
        $configuration = new UsersRequestBuilderGetRequestConfiguration();
        $configuration->queryParameters = new UsersRequestBuilderGetQueryParameters();
        // Only request specific properties
        $configuration->queryParameters->select = ['displayName','id','mail'];
        // Sort by display name
        $configuration->queryParameters->orderby = ['displayName'];
        // Get at most 25 results
        $configuration->queryParameters->top = 25;
    
        return GraphHelper::$appClient->users()->get($configuration)->wait();
    }
    
  2. メイン.phpの空のlistUsers関数次のように置き換えます。

    function listUsers(): void {
        try {
            $users = GraphHelper::getUsers();
    
            // Output each user's details
            foreach ($users->getValue() as $user) {
                print('User: '.$user->getDisplayName().PHP_EOL);
                print('  ID: '.$user->getId().PHP_EOL);
                $email = $user->getMail();
                $email = isset($email) ? $email : 'NO EMAIL';
                print('  Email: '.$email.PHP_EOL);
            }
    
            $nextLink = $users->getOdataNextLink();
            $moreAvailable = isset($nextLink) && $nextLink != '' ? 'True' : 'False';
            print(PHP_EOL.'More users available? '.$moreAvailable.PHP_EOL.PHP_EOL);
        } catch (Exception $e) {
            print(PHP_EOL.'Error getting users: '.$e->getMessage().PHP_EOL.PHP_EOL);
        }
    }
    
  3. アプリを実行し、サインインし、オプション 2 を選択してユーザーを一覧表示します。

    Please choose one of the following options:
    0. Exit
    1. Display access token
    2. List users
    3. Make a Graph call
    2
    User: Adele Vance
      ID: 05fb57bf-2653-4396-846d-2f210a91d9cf
      Email: AdeleV@contoso.com
    User: Alex Wilber
      ID: a36fe267-a437-4d24-b39e-7344774d606c
      Email: AlexW@contoso.com
    User: Allan Deyoung
      ID: 54cebbaa-2c56-47ec-b878-c8ff309746b0
      Email: AllanD@contoso.com
    User: Bianca Pisani
      ID: 9a7dcbd0-72f0-48a9-a9fa-03cd46641d49
      Email: NO EMAIL
    User: Brian Johnson (TAILSPIN)
      ID: a8989e40-be57-4c2e-bf0b-7cdc471e9cc4
      Email: BrianJ@contoso.com
    
    ...
    
    More users available? true
    

コードの説明

getUsers関数のコードについて考えてみましょう。

  • ユーザーのコレクションを取得します。
  • queryParameters->selectを使用して特定のプロパティを要求します
  • queryParameters->topを使用して、返されるユーザーの数を制限します
  • queryParameters->orderbyを使用して応答を並べ替える

次の手順