Ecco un modo in cui lo sto facendo dopo averlo cercato per un po '. Volevo creare un endpoint API Laravel che controlla se un campo è "in uso", quindi le informazioni importanti sono: 1) quale tabella DB? 2) quale colonna DB? e 3) esiste un valore in quella colonna che corrisponde ai termini di ricerca?
Sapendo questo, possiamo costruire il nostro array associativo:
$SEARCHABLE_TABLE_COLUMNS = [
'users' => [ 'email' ],
];
Quindi, possiamo impostare i nostri valori che controlleremo:
$table = 'users';
$column = 'email';
$value = 'alice@bob.com';
Quindi, possiamo usare array_key_exists()e in_array()vicendevolmente per eseguire una combinazione di uno, due passaggi e quindi agire sulla truthycondizione:
// step 1: check if 'users' exists as a key in `$SEARCHABLE_TABLE_COLUMNS`
if (array_key_exists($table, $SEARCHABLE_TABLE_COLUMNS)) {
// step 2: check if 'email' is in the array: $SEARCHABLE_TABLE_COLUMNS[$table]
if (in_array($column, $SEARCHABLE_TABLE_COLUMNS[$table])) {
// if table and column are allowed, return Boolean if value already exists
// this will either return the first matching record or null
$exists = DB::table($table)->where($column, '=', $value)->first();
if ($exists) return response()->json([ 'in_use' => true ], 200);
return response()->json([ 'in_use' => false ], 200);
}
// if $column isn't in $SEARCHABLE_TABLE_COLUMNS[$table],
// then we need to tell the user we can't proceed with their request
return response()->json([ 'error' => 'Illegal column name: '.$column ], 400);
}
// if $table isn't a key in $SEARCHABLE_TABLE_COLUMNS,
// then we need to tell the user we can't proceed with their request
return response()->json([ 'error' => 'Illegal table name: '.$table ], 400);
Mi scuso per il codice PHP specifico di Laravel, ma lo lascerò perché penso che tu possa leggerlo come pseudo-codice. La parte importante sono le due ifistruzioni che vengono eseguite in modo sincrono.
array_key_exists()e in_array()sono funzioni PHP.
fonte:
La cosa bella l'algoritmo che ho mostrato sopra è che si può fare un endpoint REST, come GET /in-use/{table}/{column}/{value}(dove table, columne valuesono variabili).
Potresti avere:
$SEARCHABLE_TABLE_COLUMNS = [
'accounts' => [ 'account_name', 'phone', 'business_email' ],
'users' => [ 'email' ],
];
e quindi è possibile effettuare richieste GET come:
GET /in-use/accounts/account_name/Bob's Drywall (potrebbe essere necessario codificare uri l'ultima parte, ma di solito no)
GET /in-use/accounts/phone/888-555-1337
GET /in-use/users/email/alice@bob.com
Si noti inoltre che nessuno può fare:
GET /in-use/users/password/dogmeat1337perché passwordnon è elencato nel tuo elenco di colonne consentite per user.
Buona fortuna per il tuo viaggio