PHP: If ... Else ... Sorgu

3 Cevap

I while (($data=fgetcsv($this->fin,5000,";"))!==FALSE) altında bu deyimi yürütme am

Şimdi ne başka döngüde istiyorsanız eğer koşulu tatmin etmedi yalnızca veri değeri için istisna etmektir. Ben sadece değerini tatmin olmayan veriler için özel durum nasıl emin değilim şu anda tam bir satır görüntüleyerek duyuyorum.

Code

if ((strtotime($data[11]) &&strtotime($data[12])&&strtotime($data[16]))!==FALSE 
&& ctype_digit($data[0]) && ctype_alnum($data[1]) && ctype_digit($data[2]) 
&& ctype_alnum($data[3]) && ctype_alnum($data[4]) && ctype_alnum($data[5]) 
&& ctype_alnum($data[6]) && ctype_alnum($data[7]) && ctype_alnum($data[8]) 
&& $this->_is_valid($data[9]) && ctype_digit($data[10]) && ctype_digit($data[13]) 
&& $this->_is_valid($data[14]))
{
     //Some Logic
}
else
{
    throw new Exception ("Data {$data[0], $data[1], $data[2], $data[3],
    $data[4], $data[5], $data[6], $data[7],
    $data[8], $data[9], $data[10], $data[11], $data[12],
    $data[13], $data[14], $data[16]} is not in valid format");
}

Rehberlik derece Ben sadece eğer değerini tatmin etmedi veriler için özel durum nasıl olarak mutluluk duyacağız.

3 Cevap

Neden testleri ayrı değildir? yani, her testi tek tek yapmak ve belirli bir test başarısız olursa bir istisna?


Copy-pasting from your code, it would probably look like this :

if (!strtotime($data[11])) {
    throw new Exception("field 11 : {$data[11]} is not a valid date");
}
if (!strtotime($data[12])) {
    throw new Exception("field 12 : {$data[12]} is not a valid date");
}
// Some more...
if (!ctype_alnum($data[8])) {
    throw new Exception("field 8 : {$data[8]} is not a valid alnum");
}
// And so on...

// And when all is tested, you know the items 
// in $data are all OK


This way :

  • Eğer bir doğrulama hatası neden olan tarla biliyorsunuz
  • Eğer aynı alanda birkaç farklı testler varsa, özel test başarısız hangi biliyorsunuz

Bazı durumlarda, bu yararlı olabilir - Ve, bir olasılık olarak, size (if needed) (i.e. one kind of exception for dates, one for integers, ...) başarısız teste bağlı olarak, istisnalar farklı tür atılmış olabilir.



Edit after the comment : more full example

Evet, alana göre alan doğrulamak ve hala satır satır çalışabilir.

Sen sadece bir try / catch bloğu içinde test kodu kaydırmak zorunda, o satır satır gider döngü içinde bulunuyor; Böyle bir bit:

$validData = array();
$errors = array();

while ($data = fgetcsv($f)) {
    try {
        // Validate the data of the current line
        // And, if valid, insert it into the database

        if (!strtotime($data[11])) {
            throw new Exception("field 11 : {$data[11]} is not a valid date");
        }
        if (!strtotime($data[12])) {
            throw new Exception("field 12 : {$data[12]} is not a valid date");
        }
        // Some more...
        if (!ctype_alnum($data[8])) {
            throw new Exception("field 8 : {$data[8]} is not a valid alnum");
        }
        // And so on...

        // And when all is tested, you know the items 
        // in $data are all OK
        // => which means it can be inserted into the DB
        // Or you can just put the valid data into a "temporary" array, that will be used later :
        $validData[] = $data;

    } catch (Exception $e) {
        // An error has occurend on the current line
        // You can log it, if necessary :
        $errors[] = $e->getMessage();
    }
}

// Now that the whole file has been read, test if there's been an error :
if (empty($errors)) {
    // No error
    // => insert the data that's in $validData
} else {
    // There's been an error
    // => don't insert the data that's in $validData, if you don't want to insert anything
}


With that :

  • Bir satır (i.e. validation fails) üzerine bir istisna varsa, sen sorunu ile başa çıkmak için, catch bloğuna atlarsınız
  • Ve döngü sonra bir sonraki satırda için, yeniden başlayacaktır.

EDIT: (By Yacoby)
Rather than having endless if statments, you could just define which elements should be checked by which function and then process them in a loop. That way it avoids having 16 if statements.

Kod örneği:

foreach ( array(11,12,16) as $index ){
    if ( !strtotime($data[$i]) ){
        throw new Exception("field {$i} : {$data[$i]} is not a date");
    }
}

foreach ( array(1,3,4,5,6,7,8) as $index ){
    if ( !ctype_alnum($data[$i]) ){
        throw new Exception("field {$i} : {$data[$i]} is not alphanumeric");
    }
}

foreach ( array(2, 10) as $i ){
    if ( !ctype_digit($data[$i]) ){
        throw new Exception("field {$i} : {$data[$i]} is not a valid digit");
    }
}

if ( !$this->_is_valid($data[14]) ){
    throw new Exception("field {14} : {$data[14]} is not valid");
}

Sen değer başına bir birine büyük if deyimi kırmak gerekir.

Seni çok içine bu kadar kesiliyor daha iyi olacağını düşünüyorum tablolar gibi eğer

if(!strtotime($data[11])
{
    throw new Exception("...");
}

if(!strtotime($data[12]))
{
    throw new Exception("...");
}


//after all of your if statements now do business logic
//remember that all of your if conditions have to be met to get this far
//because throwing the exception will leave this stack
//so it functions sort of like the else clause would.