Cara menggunakan layanan Tabel Azure Storage atau Azure Cosmos DB untuk Tabel dari PHP

BERLAKU UNTUK: Tabel

Peringatan

Proyek ini berada dalam tahap dukungan komunitas siklus hidupnya. Akhirnya, semua pustaka klien terkait akan dihentikan secara permanen. Untuk informasi selengkapnya tentang penghentian dan alternatif untuk menggunakan proyek ini, lihat Pemberitahuan penghentian: Pustaka klien PHP Azure Storage.

Tip

Konten dalam artikel ini berlaku untuk penyimpanan Azure Table dan Azure Cosmos DB for Table. API untuk Tabel adalah penawaran premium untuk penyimpanan tabel yang menawarkan tabel yang dioptimalkan throughput, distribusi global, dan indeks sekunder otomatis.

Artikel ini menunjukkan cara membuat tabel, menyimpan data Anda, dan melakukan operasi CRUD pada data. Pilih layanan Azure Table atau Azure Cosmos DB for Table. Sampel ditulis dalam PHP dan menggunakan Pustaka Klien PHP Tabel Azure Storage. Skenario yang dibahas meliputi membuat dan menghapus tabel, dan menyisipkan, menghapus, dan mengkueri entitas dalam tabel.

Membuat akun layanan Azure

Anda dapat bekerja dengan tabel menggunakan penyimpanan Azure Table atau Azure Cosmos DB. Untuk mempelajari selengkapnya tentang perbedaan antara penawaran tabel di dua layanan ini, lihat gambaran umum API untuk Tabel. Anda perlu membuat akun untuk layanan yang akan Anda gunakan. Bagian berikut menunjukkan cara membuat penyimpanan Azure Table dan akun Azure Cosmos DB, tetapi Anda bisa menggunakan salah satunya.

Azure Table Storage

Cara termudah untuk membuat akun penyimpanan Azure adalah dengan menggunakan portal Azure. Untuk mempelajari lebih lanjut, lihat Membuat akun penyimpanan.

Anda juga bisa membuat akun penyimpanan Azure dengan menggunakan Azure PowerShell atau Azure CLI.

Jika Anda lebih suka tidak membuat akun penyimpanan saat ini, Anda juga dapat menggunakan Azure Storage emulator untuk menjalankan dan menguji kode Anda di lingkungan lokal. Untuk informasi selengkapnya, lihat Menggunakan Azure Storage Emulator untuk pengembangan dan pengujian.

Azure Cosmos DB for Table

Untuk instruksi tentang membuat akun Azure Cosmos DB for Table, lihat Membuat akun database.

Membuat aplikasi PHP

Satu-satunya persyaratan untuk membuat aplikasi PHP untuk mengakses layanan Tabel Penyimpanan atau Azure Cosmos DB for Table adalah dengan mereferensikan kelas di azure-storage-table SDK untuk PHP dari dalam kode Anda. Anda dapat menggunakan alat pengembangan apa pun untuk membuat aplikasi Anda, termasuk Notepad.

Dalam panduan ini, Anda menggunakan fitur Azure Table Storage atau Azure Cosmos DB untuk Tabel yang dapat dipanggil dari dalam aplikasi PHP. Aplikasi dapat berjalan secara lokal atau dalam kode yang berjalan dalam peran web Azure, peran pekerja, atau situs web.

Mendapatkan pustaka klien

  1. Buat file bernama composer.json di akar proyek Anda dan tambahkan kode berikut ke dalamnya:

    {
    "require": {
     "microsoft/azure-storage-table": "*"
    }
    }
    
  2. Unduh composer.phar di root Anda.

  3. Membuka prompt perintah dan jalankan perintah berikut ini di akar proyek Anda:

    php composer.phar install
    

    Atau buka Pustaka Klien Azure Storage PHP pada GitHub untuk mengkloning kode sumber.

Menambahkan referensi yang diperlukan

Untuk menggunakan layanan Tabel Penyimpanan atau API Azure Cosmos DB, Anda harus:

  • Referensikan file autoloader menggunakan pernyataan require_once, dan
  • Referensikan kelas apa pun yang Anda gunakan.

Contoh berikut menunjukkan cara menyertakan file pemuat otomatis dan mereferensikan kelas TableRestProxy.

require_once 'vendor/autoload.php';
use MicrosoftAzure\Storage\Table\TableRestProxy;

Dalam contoh di sini, require_once pernyataan selalu ditampilkan, tetapi hanya kelas yang diperlukan untuk contoh yang dijalankan yang dirujuk.

Menambahkan string koneksi Anda

Anda dapat menyambungkan ke akun penyimpanan Azure atau akun Azure Cosmos DB for Table. Dapatkan string koneksi berdasarkan jenis akun yang Anda gunakan.

Menambahkan koneksi layanan Tabel Penyimpanan

Untuk membuat contoh klien layanan Storage Table, Anda harus terlebih dahulu memiliki string koneksi yang valid. Format untuk string koneksi layanan Tabel Penyimpanan adalah:

$connectionString = "DefaultEndpointsProtocol=[http|https];AccountName=[yourAccount];AccountKey=[yourKey]"

Menambahkan koneksi Emulator Penyimpanan

Untuk mengakses penyimpanan emulator:

UseDevelopmentStorage = true

Menambahkan sambungan Azure Cosmos DB

Untuk membuat contoh klien Tabel Azure Cosmos DB, Anda harus terlebih dahulu memiliki string koneksi yang valid. Format string koneksi Azure Cosmos DB adalah:

$connectionString = "DefaultEndpointsProtocol=[https];AccountName=[myaccount];AccountKey=[myaccountkey];TableEndpoint=[https://myendpoint/]";

Untuk membuat klien layanan Azure Table atau klien Azure Cosmos DB, Anda harus menggunakan kelas TableRestProxy. Anda dapat:

  • Berikan string koneksi langsung ke dalamnya atau
  • Gunakan CloudConfigurationManager (CCM) untuk memeriksa beberapa sumber eksternal untuk string koneksi:
    • Secara default, disertai dengan dukungan untuk satu sumber eksternal - variabel lingkungan.
    • Anda bisa menambahkan sumber baru dengan memperluaskan kelas ConnectionStringSource.

Pada contoh yang diuraikan di sini, string koneksi diteruskan secara langsung.

require_once 'vendor/autoload.php';

use MicrosoftAzure\Storage\Table\TableRestProxy;

$tableClient = TableRestProxy::createTableService($connectionString);

Membuat tabel

Objek TableRestProxy memungkinkan Anda membuat tabel dengan metode createTable. Saat membuat tabel, Anda bisa mengatur batas waktu layanan Tabel habis. Untuk informasi selengkapnya tentang batas waktu layanan Tabel, lihat Mengatur Batas Waktu untuk Operasi Layanan Tabel.

require_once 'vendor\autoload.php';

use MicrosoftAzure\Storage\Table\TableRestProxy;
use MicrosoftAzure\Storage\Common\Exceptions\ServiceException;

// Create Table REST proxy.
$tableClient = TableRestProxy::createTableService($connectionString);

try    {
    // Create table.
    $tableClient->createTable("mytable");
}
catch(ServiceException $e){
    $code = $e->getCode();
    $error_message = $e->getMessage();
    // Handle exception based on error codes and messages.
    // Error codes and messages can be found here:
    // https://learn.microsoft.com/rest/api/storageservices/Table-Service-Error-Codes
}

Untuk informasi tentang pembatasan nama tabel, lihat Memahami Model Data Layanan Tabel.

Menambahkan entitas ke tabel

Untuk menambahkan entitas ke tabel, buat objek Entitas baru dan serahkan ke TableRestProxy->InsertEntity. Saat membuat entitas, Anda harus menentukan PartitionKey dan RowKey. Entitas ini adalah pengidentifikasi unik untuk entitas dan merupakan nilai yang dapat dikueri lebih cepat daripada properti entitas lainnya. Sistem ini digunakan PartitionKey untuk secara otomatis mendistribusikan entitas tabel di atas banyak node Penyimpanan. Entitas dengan PartitionKeyPartitionKey yang sama disimpan pada simpul yang sama. Operasi pada beberapa entitas yang disimpan pada simpul yang sama berkinerja lebih baik daripada pada entitas yang disimpan di berbagai simpul. ID RowKey unik entitas di dalam partisi.

require_once 'vendor/autoload.php';

use MicrosoftAzure\Storage\Table\TableRestProxy;
use MicrosoftAzure\Storage\Common\Exceptions\ServiceException;
use MicrosoftAzure\Storage\Table\Models\Entity;
use MicrosoftAzure\Storage\Table\Models\EdmType;

// Create table REST proxy.
$tableClient = TableRestProxy::createTableService($connectionString);

$entity = new Entity();
$entity->setPartitionKey("tasksSeattle");
$entity->setRowKey("1");
$entity->addProperty("Description", null, "Take out the trash.");
$entity->addProperty("DueDate",
                        EdmType::DATETIME,
                        new DateTime("2012-11-05T08:15:00-08:00"));
$entity->addProperty("Location", EdmType::STRING, "Home");

try{
    $tableClient->insertEntity("mytable", $entity);
}
catch(ServiceException $e){
    // Handle exception based on error codes and messages.
    // Error codes and messages are here:
    // https://learn.microsoft.com/rest/api/storageservices/Table-Service-Error-Codes
    $code = $e->getCode();
    $error_message = $e->getMessage();
}

Untuk informasi tentang properti dan tipe tabel, lihat Memahami Model Data Layanan Tabel.

Class TableRestProxy menawarkan dua metode alternatif untuk menyisipkan entitas: insertOrMergeEntity dan insertOrReplaceEntity. Untuk menggunakan metode ini, buat Entitas baru dan luluskan sebagai parameter ke salah satu metode. Setiap metode menyisipkan entitas jika tidak ada. Jika entitas sudah ada, insertOrMergeEntity memperbarui nilai properti jika properti sudah ada dan menambahkan properti baru jika tidak ada, sementara insertOrReplaceEntity sepenuhnya menggantikan entitas yang ada. Contoh berikut menunjukkan cara menggunakan insertOrMergeEntity. Jika entitas dengan PartitionKey "tasksSeattle" dan RowKey "1" belum ada, entitas tersebut kemudian dimasukkan. Namun, jika sudah ada (seperti yang ditunjukkan pada contoh sebelumnya), DueDate properti diperbarui, dan Status properti ditambahkan. Properti Description juga Location diperbarui, tetapi dengan nilai yang secara efektif membiarkannya tidak berubah. Jika kedua properti terakhir ini tidak ditambahkan seperti yang ditunjukkan dalam contoh, tetapi ada pada entitas target, nilai yang ada akan tetap tidak berubah.

require_once 'vendor/autoload.php';

use MicrosoftAzure\Storage\Table\TableRestProxy;
use MicrosoftAzure\Storage\Common\Exceptions\ServiceException;
use MicrosoftAzure\Storage\Table\Models\Entity;
use MicrosoftAzure\Storage\Table\Models\EdmType;

// Create table REST proxy.
$tableClient = TableRestProxy::createTableService($connectionString);

//Create new entity.
$entity = new Entity();

// PartitionKey and RowKey are required.
$entity->setPartitionKey("tasksSeattle");
$entity->setRowKey("1");

// If entity exists, existing properties are updated with new values and
// new properties are added. Missing properties are unchanged.
$entity->addProperty("Description", null, "Take out the trash.");
$entity->addProperty("DueDate", EdmType::DATETIME, new DateTime()); // Modified the DueDate field.
$entity->addProperty("Location", EdmType::STRING, "Home");
$entity->addProperty("Status", EdmType::STRING, "Complete"); // Added Status field.

try    {
    // Calling insertOrReplaceEntity, instead of insertOrMergeEntity as shown,
    // would simply replace the entity with PartitionKey "tasksSeattle" and RowKey "1".
    $tableClient->insertOrMergeEntity("mytable", $entity);
}
catch(ServiceException $e){
    // Handle exception based on error codes and messages.
    // Error codes and messages are here:
    // https://learn.microsoft.com/rest/api/storageservices/Table-Service-Error-Codes
    $code = $e->getCode();
    $error_message = $e->getMessage();
    echo $code.": ".$error_message."<br />";
}

Mengambil satu entitas

Metode GetEntity TableRestProxy->getEntity memungkinkan Anda untuk mengambil satu entitas dengan meminta PartitionKey dan RowKey. Dalam contoh di sini, kunci tasksSeattle partisi dan kunci 1 baris diteruskan ke metode getEntity .

require_once 'vendor/autoload.php';

use MicrosoftAzure\Storage\Table\TableRestProxy;
use MicrosoftAzure\Storage\Common\Exceptions\ServiceException;

// Create table REST proxy.
$tableClient = TableRestProxy::createTableService($connectionString);

try    {
    $result = $tableClient->getEntity("mytable", "tasksSeattle", 1);
}
catch(ServiceException $e){
    // Handle exception based on error codes and messages.
    // Error codes and messages are here:
    // https://learn.microsoft.com/rest/api/storageservices/Table-Service-Error-Codes
    $code = $e->getCode();
    $error_message = $e->getMessage();
    echo $code.": ".$error_message."<br />";
}

$entity = $result->getEntity();

echo $entity->getPartitionKey().":".$entity->getRowKey();

Mengambil semua entitas dalam partisi

Kueri entitas dibangun menggunakan filter. Untuk informasi selengkapnya, lihat Mengkueri Tabel dan Entitas. Untuk mengambil semua entitas dalam partisi, gunakan filter PartitionKey eq partition_name. Contoh berikut menunjukkan cara mengambil semua entitas dalam tasksSeattle partisi dengan meneruskan filter ke metode queryEntities.

require_once 'vendor/autoload.php';

use MicrosoftAzure\Storage\Table\TableRestProxy;
use MicrosoftAzure\Storage\Common\Exceptions\ServiceException;

// Create table REST proxy.
$tableClient = TableRestProxy::createTableService($connectionString);

$filter = "PartitionKey eq 'tasksSeattle'";

try    {
    $result = $tableClient->queryEntities("mytable", $filter);
}
catch(ServiceException $e){
    // Handle exception based on error codes and messages.
    // Error codes and messages are here:
    // https://learn.microsoft.com/rest/api/storageservices/Table-Service-Error-Codes
    $code = $e->getCode();
    $error_message = $e->getMessage();
    echo $code.": ".$error_message."<br />";
}

$entities = $result->getEntities();

foreach($entities as $entity){
    echo $entity->getPartitionKey().":".$entity->getRowKey()."<br />";
}

Mengambil subset entitas dalam partisi

Pola yang sama yang digunakan dalam contoh sebelumnya dapat digunakan untuk mengambil subkumpulan entitas dalam partisi. Filter yang Anda gunakan menentukan subset entitas yang Anda ambil. Untuk informasi selengkapnya, lihat Mengkueri Tabel dan Entitas. Contoh berikut menunjukkan cara menggunakan filter untuk mengambil semua entitas dengan tanggal tertentu Location dan DueDate kurang dari tanggal yang ditentukan.

require_once 'vendor/autoload.php';

use MicrosoftAzure\Storage\Table\TableRestProxy;
use MicrosoftAzure\Storage\Common\Exceptions\ServiceException;

// Create table REST proxy.
$tableClient = TableRestProxy::createTableService($connectionString);

$filter = "Location eq 'Office' and DueDate lt '2012-11-5'";

try    {
    $result = $tableClient->queryEntities("mytable", $filter);
}
catch(ServiceException $e){
    // Handle exception based on error codes and messages.
    // Error codes and messages are here:
    // https://learn.microsoft.com/rest/api/storageservices/Table-Service-Error-Codes
    $code = $e->getCode();
    $error_message = $e->getMessage();
    echo $code.": ".$error_message."<br />";
}

$entities = $result->getEntities();

foreach($entities as $entity){
    echo $entity->getPartitionKey().":".$entity->getRowKey()."<br />";
}

Mengambil subset properti entitas

Kueri dapay mengambil subset properti entitas. Teknik ini, yang disebut proyeksi, mengurangi bandwidth dan dapat meningkatkan performa kueri, terutama untuk entitas besar. Untuk menentukan properti yang akan diambil, berikan nama properti ke Query->addSelectField metode . Anda dapat memanggil metode ini beberapa kali untuk menambahkan lebih banyak properti. Setelah Anda menjalankan TableRestProxy->queryEntities, entitas yang dikembalikan hanya akan memiliki properti yang dipilih. Jika Anda ingin mengembalikan subset entitas Tabel, gunakan filter seperti yang diperlihatkan dalam kueri sebelumnya.

require_once 'vendor/autoload.php';

use MicrosoftAzure\Storage\Table\TableRestProxy;
use MicrosoftAzure\Storage\Common\Exceptions\ServiceException;
use MicrosoftAzure\Storage\Table\Models\QueryEntitiesOptions;

// Create table REST proxy.
$tableClient = TableRestProxy::createTableService($connectionString);

$options = new QueryEntitiesOptions();
$options->addSelectField("Description");

try    {
    $result = $tableClient->queryEntities("mytable", $options);
}
catch(ServiceException $e){
    // Handle exception based on error codes and messages.
    // Error codes and messages are here:
    // https://learn.microsoft.com/rest/api/storageservices/Table-Service-Error-Codes
    $code = $e->getCode();
    $error_message = $e->getMessage();
    echo $code.": ".$error_message."<br />";
}

// All entities in the table are returned, regardless of whether
// they have the Description field.
// To limit the results returned, use a filter.
$entities = $result->getEntities();

foreach($entities as $entity){
    $description = $entity->getProperty("Description")->getValue();
    echo $description."<br />";
}

Memperbarui entitas

Anda dapat memperbarui entitas yang ada dengan menggunakan metode Entity->setProperty dan Entity->addProperty pada entitas, lalu memanggil TableRestProxy->updateEntity. Contoh berikut mengambil entitas, memodifikasi satu properti, menghapus properti lain, dan menambahkan properti baru. Anda dapat menghapus properti dengan mengatur nilainya menjadi null.

require_once 'vendor/autoload.php';

use MicrosoftAzure\Storage\Table\TableRestProxy;
use MicrosoftAzure\Storage\Common\Exceptions\ServiceException;
use MicrosoftAzure\Storage\Table\Models\Entity;
use MicrosoftAzure\Storage\Table\Models\EdmType;

// Create table REST proxy.
$tableClient = TableRestProxy::createTableService($connectionString);

$result = $tableClient->getEntity("mytable", "tasksSeattle", 1);

$entity = $result->getEntity();
$entity->setPropertyValue("DueDate", new DateTime()); //Modified DueDate.
$entity->setPropertyValue("Location", null); //Removed Location.
$entity->addProperty("Status", EdmType::STRING, "In progress"); //Added Status.

try    {
    $tableClient->updateEntity("mytable", $entity);
}
catch(ServiceException $e){
    // Handle exception based on error codes and messages.
    // Error codes and messages are here:
    // https://learn.microsoft.com/rest/api/storageservices/Table-Service-Error-Codes
    $code = $e->getCode();
    $error_message = $e->getMessage();
    echo $code.": ".$error_message."<br />";
}

Menghapus entitas

Untuk menghapus entitas, lewati nama tabel, dan PartitionKey entitas serta RowKey ke metode TableRestProxy->deleteEntity.

require_once 'vendor/autoload.php';

use MicrosoftAzure\Storage\Table\TableRestProxy;
use MicrosoftAzure\Storage\Common\Exceptions\ServiceException;

// Create table REST proxy.
$tableClient = TableRestProxy::createTableService($connectionString);

try    {
    // Delete entity.
    $tableClient->deleteEntity("mytable", "tasksSeattle", "2");
}
catch(ServiceException $e){
    // Handle exception based on error codes and messages.
    // Error codes and messages are here:
    // https://learn.microsoft.com/rest/api/storageservices/Table-Service-Error-Codes
    $code = $e->getCode();
    $error_message = $e->getMessage();
    echo $code.": ".$error_message."<br />";
}

Untuk pemeriksaan konkurensi, Anda dapat mengatur Etag untuk entitas yang akan dihapus dengan menggunakan metode DeleteEntityOptions->setEtag dan meneruskan objek DeleteEntityOptions ke deleteEntity sebagai parameter keempat.

Operasi tabel batch

Metode TableRestProxy->batch memungkinkan Anda untuk menjalankan beberapa operasi dalam satu permintaan. Pola di sini melibatkan penambahan operasi ke objek BatchRequest dan kemudian meneruskan objek BatchRequest ke metode TableRestProxy->batch. Untuk menambahkan operasi ke objek BatchRequest, Anda dapat memanggil salah satu metode berikut beberapa kali:

Deskripsi
addInsertEntity Menambahkan operasi insertEntity
addUpdateEntity Menambahkan operasi updateEntity
addMergeEntity Menambahkan operasi mergeEntity
addInsertOrReplaceEntity Menambahkan operasi insertOrReplaceEntity
addInsertOrMergeEntity Menambahkan operasi insertOrMergeEntity
addDeleteEntity Menambahkan operasi deleteEntity

Contoh berikut menunjukkan cara menjalankan operasi insertEntity dan deleteEntity dalam satu permintaan.

require_once 'vendor/autoload.php';

use MicrosoftAzure\Storage\Table\TableRestProxy;
use MicrosoftAzure\Storage\Common\Exceptions\ServiceException;
use MicrosoftAzure\Storage\Table\Models\Entity;
use MicrosoftAzure\Storage\Table\Models\EdmType;
use MicrosoftAzure\Storage\Table\Models\BatchOperations;

// Configure a connection string for Storage Table service.
$connectionString = "DefaultEndpointsProtocol=[http|https];AccountName=[yourAccount];AccountKey=[yourKey]"

// Create table REST proxy.
$tableClient = TableRestProxy::createTableService($connectionString);

// Create list of batch operation.
$operations = new BatchOperations();

$entity1 = new Entity();
$entity1->setPartitionKey("tasksSeattle");
$entity1->setRowKey("2");
$entity1->addProperty("Description", null, "Clean roof gutters.");
$entity1->addProperty("DueDate",
                        EdmType::DATETIME,
                        new DateTime("2012-11-05T08:15:00-08:00"));
$entity1->addProperty("Location", EdmType::STRING, "Home");

// Add operation to list of batch operations.
$operations->addInsertEntity("mytable", $entity1);

// Add operation to list of batch operations.
$operations->addDeleteEntity("mytable", "tasksSeattle", "1");

try    {
    $tableClient->batch($operations);
}
catch(ServiceException $e){
    // Handle exception based on error codes and messages.
    // Error codes and messages are here:
    // https://learn.microsoft.com/rest/api/storageservices/Table-Service-Error-Codes
    $code = $e->getCode();
    $error_message = $e->getMessage();
    echo $code.": ".$error_message."<br />";
}

Untuk informasi selengkapnya tentang batching operasi Tabel, lihat Melakukan Transaksi Grup Entitas.

Menghapus tabel

Terakhir, untuk menghapus tabel, berikan nama tabel ke metode TableRestProxy->deleteTable.

require_once 'vendor/autoload.php';

use MicrosoftAzure\Storage\Table\TableRestProxy;
use MicrosoftAzure\Storage\Common\Exceptions\ServiceException;

// Create table REST proxy.
$tableClient = TableRestProxy::createTableService($connectionString);

try    {
    // Delete table.
    $tableClient->deleteTable("mytable");
}
catch(ServiceException $e){
    // Handle exception based on error codes and messages.
    // Error codes and messages are here:
    // https://learn.microsoft.com/rest/api/storageservices/Table-Service-Error-Codes
    $code = $e->getCode();
    $error_message = $e->getMessage();
    echo $code.": ".$error_message."<br />";
}