문제

가장 좋은 방법은 무엇성 평 파일 데이터베이스 구조에서 PHP?

많이 더 성숙한 PHP 평 파일에 프레임워크를 나는 거기에 시도를 구현하는 SQL 쿼리를 구상에 대한 내 용에 대부분의 경우(나는 그 데이터베이스를 사용하여 그 시점에서).

이 있습한 트릭을 할 수 밖에 없 좋은 성능과 기능과 함께 작은 코드 오버헤드?

도움이 되었습니까?

해결책

만,무엇이 자연의 평 데이터베이스가 있습니다.그들은 크고 작은.그것은 간단한 어레이 배열에까요?면 간단하게 뭔가를 말하는 사용자 프로필을 구축 등과 같은:

$user = array("name" => "dubayou", 
              "age" => 20,
              "websites" => array("dubayou.com","willwharton.com","codecream.com"),
              "and_one" => "more");

을 저장하거나 업데이트 db 기록 에서 사용자를 선택합니다.

$dir = "../userdata/";  //make sure to put it bellow what the server can reach.
file_put_contents($dir.$user['name'],serialize($user));

및 로드 기록 사용자

function &get_user($name){
    return unserialize(file_get_contents("../userdata/".$name));
}

그러나 다시는 이 구현에 따라 달라질 수는 응용 프로그램과 자연의 데이터베이스를 필요합니다.

다른 팁

고려할 수 있습니다 SQLite.그것은 거의 간단한 플랫 파일로,하지만 당신은 당신을 얻을 SQL 엔진에 대한 쿼리.그 잘 PHP 너무입니다.

내 생각에 사용하여,"편평한 파일 데이터베이스"의미에서 당신은미(고 대답을 허용)지 않 neccesarily 가장 좋은 방법에 대해 이동하는 것들입니다.첫째,사용 serialize()unserialize() 일으킬 수 있는 중요한 두통 사람이 면서 및 편집하는 파일(그들이 할 수있는,사실에 넣어 arbritrary 코드에서"데이터베이스"를 실행됩니다.)

개인적으로 말한 이유 없는 미래를 보는?이 있었다 너무 많은 시간을 내가 문제가 있었기 때문이었을 만드는 내 자신의"소유"파일,프로젝트의 폭발 지점에 필요한 데이터베이스,그리고 제가 생각해보니"당신이 알고,나는 내가 이를 위한 데이터베이스를 시작으로"-기 때문이터베이스의 코드 방법으로 너무 많은 시간과 노력이 필요합니다.

이에서 내가 배운 미래를 교정 내 응용 프로그램 그래서 그 때 그것을 가져 더 큰 나는 가야 하지 않고 일을 보낼 refactoring 방법은 앞으로 이동합니다.어떻게 해야 하나요?

SQLite.그것은 작품으로 데이터베이스를 사용하여 SQL,그리고 아주 쉽게 변경 mySQL(espescially 를 사용하는 경우 추상 클래스는 데이터베이스에 대한 조작과 같은 난!)

사실,espescially 과"허용된"대답's 방법,그것은 크게 잘라 메모리의 사용은 응용 프로그램(당신이 없을 로드하는 모든"기록"로 PHP)

하나의 프레임워크를 아는 것에 대한 블로그 플랫폼입니다.이후 그냥에 대한 모든 가능한 데이터를 보다 원하는 것이 될 것으로 분류 날짜 생각했다,이것에 대해 구조

한 디렉토리당 콘텐츠 노드:

./content/YYYYMMDDHHMMSS/

하위 디렉토리의 각 노드를 포함하여

/tags  
/authors  
/comments  

뿐만 아니라 간단한 텍스트 파일에서 노드에 대한 디렉토리 pre-and post-렌더링되는 콘텐츠와 같습니다.

이 수 있는 간단한 PHP glob() 전화(아마의 반전의 결과 배열)쿼리에 단지에 대해 아무것도 내에서 콘텐츠 구조

glob("content/*/tags/funny");  

반환하는 경로를 포함하여 모든 기사를 태그"재미".

여기에는 코드는 우리가 사용하는을 위한 Lilina:

<?php
/**
 * Handler for persistent data files
 *
 * @author Ryan McCue <cubegames@gmail.com>
 * @package Lilina
 * @version 1.0
 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
 */

/**
 * Handler for persistent data files
 *
 * @package Lilina
 */
class DataHandler {
    /**
     * Directory to store data.
     *
     * @since 1.0
     *
     * @var string
     */
    protected $directory;

    /**
     * Constructor, duh.
     *
     * @since 1.0
     * @uses $directory Holds the data directory, which the constructor sets.
     *
     * @param string $directory 
     */
    public function __construct($directory = null) {
        if ($directory === null)
            $directory = get_data_dir();

        if (substr($directory, -1) != '/')
            $directory .= '/';

        $this->directory = (string) $directory;
    }

    /**
     * Prepares filename and content for saving
     *
     * @since 1.0
     * @uses $directory
     * @uses put()
     *
     * @param string $filename Filename to save to
     * @param string $content Content to save to cache
     */
    public function save($filename, $content) {
        $file = $this->directory . $filename;

        if(!$this->put($file, $content)) {
            trigger_error(get_class($this) . " error: Couldn't write to $file", E_USER_WARNING);
            return false;
        }

        return true;
    }

    /**
     * Saves data to file
     *
     * @since 1.0
     * @uses $directory
     *
     * @param string $file Filename to save to
     * @param string $data Data to save into $file
     */
    protected function put($file, $data, $mode = false) {
        if(file_exists($file) && file_get_contents($file) === $data) {
            touch($file);
            return true;
        }

        if(!$fp = @fopen($file, 'wb')) {
            return false;
        }

        fwrite($fp, $data);
        fclose($fp);

        $this->chmod($file, $mode);
        return true;

    }

    /**
     * Change the file permissions
     *
     * @since 1.0
     *
     * @param string $file Absolute path to file
     * @param integer $mode Octal mode
     */
    protected function chmod($file, $mode = false){
        if(!$mode)
            $mode = 0644;
        return @chmod($file, $mode);
    }

    /**
     * Returns the content of the cached file if it is still valid
     *
     * @since 1.0
     * @uses $directory
     * @uses check() Check if cache file is still valid
     *
     * @param string $id Unique ID for content type, used to distinguish between different caches
     * @return null|string Content of the cached file if valid, otherwise null
     */
    public function load($filename) {
        return $this->get($this->directory . $filename);
    }

    /**
     * Returns the content of the file
     *
     * @since 1.0
     * @uses $directory
     * @uses check() Check if file is valid
     *
     * @param string $id Filename to load data from
     * @return bool|string Content of the file if valid, otherwise null
     */
    protected function get($filename) {
        if(!$this->check($filename))
            return null;

        return file_get_contents($filename);
    }

    /**
     * Check a file for validity
     *
     * Basically just a fancy alias for file_exists(), made primarily to be
     * overriden.
     *
     * @since 1.0
     * @uses $directory
     *
     * @param string $id Unique ID for content type, used to distinguish between different caches
     * @return bool False if the cache doesn't exist or is invalid, otherwise true
     */
    protected function check($filename){
        return file_exists($filename);
    }

    /**
     * Delete a file
     *
     * @param string $filename Unique ID
     */
    public function delete($filename) {
        return unlink($this->directory . $filename);
    }
}

?>

저장 각 항목으로 별도의 파일을 찾는 효율적인 위해 충분히 사용(더 불필요한 데이터를 로드하고 더 빠르게 저장하).

만약 당신이 이용하기 위하여 려고 하고 있는 평면 파일을 데이터를 유지,XML 을 사용하는 구조화하는 데이터입니다.PHP 가 built-in XML parser.

나는 수가 있습니다 간단한 함수 설계 데이터를 저장하는 파일입니다.판단할 수 있습니다 자신을 위해 경우에 유용합니다.는 점을 저장하는 것입 php 변수(면 그것은 하나 배열이 문자열이나 객체)하는 파일입니다.

<?php
function varname(&$var) {
    $oldvalue=$var;
    $var='AAAAB3NzaC1yc2EAAAABIwAAAQEAqytmUAQKMOj24lAjqKJC2Gyqhbhb+DmB9eDDb8+QcFI+QOySUpYDn884rgKB6EAtoFyOZVMA6HlNj0VxMKAGE+sLTJ40rLTcieGRCeHJ/TI37e66OrjxgB+7tngKdvoG5EF9hnoGc4eTMpVUDdpAK3ykqR1FIclgk0whV7cEn/6K4697zgwwb5R2yva/zuTX+xKRqcZvyaF3Ur0Q8T+gvrAX8ktmpE18MjnA5JuGuZFZGFzQbvzCVdN52nu8i003GEFmzp0Ny57pWClKkAy3Q5P5AR2BCUwk8V0iEX3iu7J+b9pv4LRZBQkDujaAtSiAaeG2cjfzL9xIgWPf+J05IQ==';
    foreach($GLOBALS as $var_name => $value) {
        if ($value === 'AAAAB3NzaC1yc2EAAAABIwAAAQEAqytmUAQKMOj24lAjqKJC2Gyqhbhb+DmB9eDDb8+QcFI+QOySUpYDn884rgKB6EAtoFyOZVMA6HlNj0VxMKAGE+sLTJ40rLTcieGRCeHJ/TI37e66OrjxgB+7tngKdvoG5EF9hnoGc4eTMpVUDdpAK3ykqR1FIclgk0whV7cEn/6K4697zgwwb5R2yva/zuTX+xKRqcZvyaF3Ur0Q8T+gvrAX8ktmpE18MjnA5JuGuZFZGFzQbvzCVdN52nu8i003GEFmzp0Ny57pWClKkAy3Q5P5AR2BCUwk8V0iEX3iu7J+b9pv4LRZBQkDujaAtSiAaeG2cjfzL9xIgWPf+J05IQ==')
        {
            $var=$oldvalue;
            return $var_name;
        }
    }
    $var=$oldvalue;
    return false;
}

function putphp(&$var, $file=false)
    {
    $varname=varname($var);
    if(!$file)
    {
        $file=$varname.'.php';
    }
    $pathinfo=pathinfo($file);
    if(file_exists($file))
    {
        if(is_dir($file))
        {
            $file=$pathinfo['dirname'].'/'.$pathinfo['basename'].'/'.$varname.'.php';
        }
    }
    file_put_contents($file,'<?php'."\n\$".$varname.'='.var_export($var, true).";\n");
    return true;
}

을 원하는 경우 인가 읽을 수 있는 결과를 사용할 수도 있습니다 이 파일의 형식:

ofaurax|27|male|something|
another|24|unknown||
...

이 방법은,당신은 하나의 파일을 디버깅할 수 있습니다 그것은(수정),쉽게 추가할 수 있는 필드가 나중에(의 끝에서 각 라인)와 PHP 코드를 간단(각 라인에,분할에 따라|).

그러나,단점은 당신이 구문 분석해야하는 전체 파일을 검색(는 경우에 당신은 수백만 개의 입력,그것을 좋아)그리고 처리해야 합 분리기에서 데이터를(예를 들면 닉은 전쟁|ordz).

이것은 영감으로 실용적인 솔루션:
https://github.com/mhgolkar/FlatFire
그것을 사용하여 여러 전략을 처리하는 데이터...
[에서 복사해 Readme 파일]

무료 또는 구조적 또는 혼합된

- STRUCTURED
Regular (table, row, column) format.
[DATABASE]
/   \
TX  TableY
    \_____________________________
    |ROW_0 Colum_0 Colum_1 Colum_2|
    |ROW_1 Colum_0 Colum_1 Colum_2|
    |_____________________________|
- FREE
More creative data storing. You can store data in any structure you want for each (free) element, its similar to storing an array with a unique "Id".
[DATABASE]
/   \
EX  ElementY (ID)
    \________________
    |Field_0 Value_0 |
    |Field_1 Value_1 |
    |Field_2 Value_2 |
    |________________|
recall [ID]: get_free("ElementY") --> array([Field_0]=>Value_0,[Field_1]=>Value_1...
- MIXD (Mixed)
Mixed databases can store both free elements and tables.If you add a table to a free db or a free element to a structured db, flat fire will automatically convert FREE or SRCT to MIXD database.
[DATABASE]
/   \
EX  TY

이럴 때,당신은 두 가지 옵션이 있습니다 당신이 피하려는 경우'로 표시 뭔가:

  1. SQLite

    익숙한 경우 PDO,설치할 수 있습니다 PDO 드라이버를 지원하는 SQLite.사용되지 않지만,나는 사용 PDO 톤으로 MySQL.나는 이에 현재 프로젝트입니다.

  2. XML

    이것은 많은 시간을 비교적 적은 양의 데이터입니다. 형식화된 데이터 읽기 경-,앞으로 커서 스타일의 클래스입니다. 이 라이브러리는 그러한 문제를 간단하게 읽 XML 문서를 객체로 액세스할 수 있는 그냥 다른 클래스의 인스턴스입니다.

그냥을 가리키는 잠재적인 문제를 평평한 파일 데이터베이스 시스템의이 유형:

data|some text|more data

row 2 data|bla hbalh|more data

...등등

문제는 세포 데이 포함되"|"또는" "그런 데이터가 손실 될 것이다.때로는 것이 더 쉽을 분할하여 문자의 조합하는 대부분의 사람들이 사용하지 않을텐데.

예를 들어:

열 분할: #$% (Shift+345)

행 splitter: ^&* (Shift+678)

텍스트 파일: test data#$%blah blah#$%^&*new row#$%new row data 2

다음 사용: explode("#$%", $data); use foreach, the explode again to separate columns

또는 아무것도에 따라 이러한 라인입니다.또한 추가 할 수 있습는 편평한 파일 데이터베이스에 대 한 좋은 시스템과 함께 작은 양의 데이터(ie.20 행),그러나이 될 거대 메모리 돼지를 위해 더 큰 데이터베이스가 있습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top