Whakapoto hononga kore ngako (F3)

Whakapoto hononga kore ngako (F3)

Kaore he whakama ki te whakapoto i nga hononga i te 13, tika? Ko te tangata timata, ehara i te mea katahi ano ka timata, me ngana ki te tuhi i tana ake Hononga Tamer i a ia e ako ana i etahi angamahi hou. Ko taku i mahi ai. He aha taku korero - te rima o nga bootstrap, he anga ngako iti me tetahi wahi wairua.

konei whakaaturangame konei waehere. Mo nga kaipānui penei i ahau 😉

Anga, tika?

Ko te tikanga ehara i a Laravel me era atu - i tenei ra ka mahi maatau ki te 65 kiropaita FatFreeFramework. Mena kei te mohio koe ki te Python Flask, ka mohio koe kua oti tenei mahi ki tetahi waahi:

#роутинг во Фласке
@app.route('/')
def hello_world():
    return 'Hello, World!'
//роутинг в Обезжиренном
$f3->route('GET /',
    function() {
        echo 'Hello, world!';
    }
);

Kaati, warewaretia. Tikiake .zip mai i waho, wetewetehia ki roto i te kōpaki, ka tuwhera i te wa ano i roto i to Kaiwhakatika Waehere Makau. Maamaa log.php ka tango i nga mea katoa /ui.

He tino ngawari nga mea katoa - kei roto i te kōpaki ui Kei a matou nga Tirohanga katoa, ki te korero ngawari ranei, nga tauira HTML kua whakahoutia ka whakaatuhia e matou ki te kaiwhakamahi ina uru ana ratou ki tetahi URL motuhake.

Anei te anga o to tatou "tono":

<?php
//Файл: index.php

// Kickstart the framework
$f3=require('lib/base.php');
$f3->set('DEBUG', 1);
if ((float)PCRE_VERSION<8.0)
    trigger_error('PCRE version is out of date');
$f3->config('config.ini');

//ВЕСЬ ОСТАЛЬНОЙ КОД БУДЕМ ПИСАТЬ ЗДЕСЬ

$f3->run();

Koina noa te mohio ki te timata. Me timata tatou ki te whakawaehere!

[mo te whanaketanga i whakamahia e au i te rohe XAMPP i runga i te Waehere Windows me te VS, tuhinga i tuhia ki Noushen]

Kāinga

Me timata ki te wharangi matua. Tika, tika?

//Файл: index.php

$f3->route('GET /',
    function($f3) { //чтобы использовать функции F3 передаем его в роут
                $view = new View; // создаем вьюшку
        echo $view->render('home.htm'); //рендерим шаблон
    }
);

Inaianei me tuhi koe i tenei tauira. Mo te ngawari i whakamahia e ahau bootstrap v5 alpfa.

Kaua e wareware ki te hanga tauira katoa ki te kōpaki ui, ki te kore ratou e kore e kitea ki te anga

<!-- Файл: ui/home.htm -->

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="<?php echo $ENCODING; ?>" />
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Пишем (код), сокращаем (ссылки)!</title>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous">
    </head>
    <body class="text-center bg-dark text-light"> <!-- темная тема ;) -->

        <!-- менюшка -->
        <nav class="m-2">
            <ul class="nav nav-pills justify-content-center">
                <li class="nav-item">
                    <a class="nav-link active" aria-current="page" href="#">Главная</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">Статья на Хабре</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="https://nikonovs.ru">Создатель</a>
                </li>
            </ul>
        </nav>

        <div class="container">
        <h1>Короткие ссылки уже здесь.</h1>

        <!-- Будем отправлять данные POST-запросом на /newLink -->
        <form class="mt-5 mb-3" action="/mi/newLink/" method="POST">
            <div class="row justify-content-center">
                <div class="col-auto">
                <label for="inputLink" class="col-form-label">Введи ссылку:</label>
                </div>
                <div class="col-auto">
                <input required placeholder="https://" type="url" name="link" id="inputLink" class="form-control mb-1" aria-describedby="inputLink">
                </div>
                <div class="col-auto">
                <button type="submit" class="btn btn-outline-primary">Сократить!</button>
                </div>
            </div>
        </form>

        <!-- немного -->
        <p class="text-left m-auto mb-5" style="max-width: 30rem;">Lorem ipsum dolor sit, amet consectetur adipisicing elit. Omnis illum molestiae hic fugiat molestias nemo, architecto beatae repellat ullam exercitationem non ab, necessitatibus maxime quod iure ipsa quam quos! Reprehenderit. Lorem ipsum dolor, sit amet consectetur adipisicing elit. Necessitatibus eos sapiente voluptates veniam sequi delectus totam tenetur praesentium obcaecati. Repudiandae quisquam, ipsa ullam corrupti molestiae minima optio nihil est modi?</p>

        <footer class="m-2">Сделано с <img width="20" height="20" src="https://image.flaticon.com/icons/svg/833/833472.svg" alt="любовью">, <a href="https://v5.getbootstrap.com/">пятым Bootstrap'ом</a>    и <a href="https://fatfreeframework.com/">без жира</a></footer>
        </div>
    </body>
</html>

Heoi ano, kei te mahi tonu ta matou wharangi matua. Ka tukuna e te puka he tono POST me tetahi hono me whakapoto.
Inaianei kua tae mai te wahanga ngahau (kaore).

Te mahi me te patengi raraunga

Me hanga he pātengi raraunga - MySQL. Mena kua whakauruhia e koe te PhpMyAdmin, katahi ka hanga he papaa raraunga hou "kaihonohono" ka whakahaere i tenei SQL:

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

CREATE TABLE IF NOT EXISTS `links` (
  `code` varchar(4) NOT NULL,
  `link` varchar(1000) NOT NULL,
  `hits` int(255) NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

ALTER TABLE `links`
  ADD UNIQUE KEY `code` (`code`);

E 3 nga mara mo ia hononga:

  1. Ko te Waehere he tohu matapōkere e 4 i muri i te rohe ka puta te ahunga whakamua, penei example.com/ABC1
  2. Hononga - Kaore i poroa hono.
  3. Patua - te maha o nga pao i runga i te hono poto.

Ka korero poto ahau ki a koe i te kaupapa o te mahi me te paataka, kaore he ngako.

<?php
//сначала нужно подключиться к БД
$db = new DBSQL(
    'mysql:host=localhost;port=3306;dbname=linker',
    'root',
    ''
);

//Дальше есть два варианда работы с данными:

//Можно установить переменную в Фреймворк c помощью обычного SQL-запроса:
$f3->set('result', $db->exec('SELECT * FROM wherever')); 
//они будут доступны в шаблонах, как <?= $resul ? >

//А можно использовать встроенный SQL Mapper:
$row = new DBSQLMapper($db, 'links');

$row->load(array('link="https://habrahabr.ru"')); //теперь из этого объекта доступны все колонки строки, где ссылка на Хабр:
$row_value = $row->somerow; //Вот так

// Естесственно можно изменять значения:
$row->link = 'https://habr.com';
$row->save(); //изменения нужно сохранить, а что вы думали

// больше информации по работе с БД доступно здесь: https://a.nikonovs.ru/MPHR Настоятельно рекомендую прочитать, хотябы с помощью переводчика, встроенного в браузер.
?>

Me timata tatou ki te whakapoto.

Tukatuka hono hou

Waihangatia he Tirohanga hou ki roto taupū, ka tukatukahia te tono mai i te puka kei te wharangi matua.

Tuatahi, me hanga he hou, engari he rite tonu ki te tauira tuatahi (home.htm) - "hono hou.htm".
I reira ka whakaatuhia e matou te hono kua poto ake nei me te maha o nga pao ki runga (ki te kite ano i enei "tatauranga", me whakapoto ano koe i taua hononga - ka noho tonu te wahitau).
Hei whakaputa i te putanga, ka whakamahia e matou te tinihanga "whakawhitinga taurangi":

<?php
//Файл: нет (пример)

//устанавливаем переменную в index'е и рендерим шаблон
$f3->set('link', $shorted_link);
$view = new View;
echo $view->render('newLink.htm');
//теперь в шаблоне можно использовать:
<?= $link ?>

A koinei te rarangi ingoa newLink.html:

<!-- Файл: newLink.htm -->

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="<?php echo $ENCODING; ?>" />
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Пишем (код), сокращаем (ссылки)!</title>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous">
    </head>
    <body class="text-center bg-dark text-light">
        <nav class="m-2">
            <ul class="nav nav-pills justify-content-center">
                <li class="nav-item">
                    <a class="nav-link" aria-current="page" href="/mi/">Главная</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">Статья на Хабре</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="https://nikonovs.ru">Создатель</a>
                </li>
            </ul>
        </nav>

        <div class="container">
        <h1>Короткие ссылки уже здесь.</h1>

        <!-- Убираем из формы функционал формы и выводим переменные -->
        <form class="mt-5 mb-3">
            <div class="row justify-content-center">
                <div class="col-auto">
                    <label for="inputLink" class="col-form-label">Сократили:</label>
                </div>
                <div class="col-auto">
                    <input disabled required type="url" name="link" id="inputLink" class="form-control disabled" aria-describedby="inputLink" value="<?= $link ?>">
                </div>
            </div>
            <p class="m-2 text-secondary">По этой ссылке перешли: `<?= $hits ?>`</p>
        </form>

        <a href="/mi/" class="mt-3 mb-5 btn btn-primary btn-lg">ВЕРНУТЬСЯ НА ГЛАВНУЮ</a>

        <footer class="m-2">Сделано с <img width="20" height="20" src="https://image.flaticon.com/icons/svg/833/833472.svg" alt="любовью">, <a href="https://v5.getbootstrap.com/">пятым Bootstrap'ом</a>    и <a href="https://fatfreeframework.com/">без жира</a></footer>
        </div>
    </body>
</html>

Ka tuhia e matou te ara ake.

$f3->route('GET|POST /newLink', //мы будем обрабатывать и POST и GET
    function($f3) {

            $db = new DBSQL( //Подключение к БД новое в каждом Роуте
                'mysql:host=localhost;port=3306;dbname=linker',
                'root',
                ''
            );

            //прекрасная функция генерации радомных символов:
            $permitted_chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
            function generate_string($input, $strength = 4) {
                $input_length = strlen($input);
                $random_string = '';
                for($i = 0; $i < $strength; $i++) {
                    $random_character = $input[mt_rand(0, $input_length - 1)];
                    $random_string .= $random_character;
                }

                return $random_string;
            }

            //проверка на повторение link - нам же не нужно чтобы каждый раз генерировались новые ссылки. link - уникальный.
            $check = new DBSQLMapper($db,'links');
            $check->load(array('link="'. $link .'"'));
            if ($check->dry()) {
                $g_code = generate_string($permitted_chars);
                $row = new DBSQLMapper($db,'links');
                $row->reset();
                $row->code = $g_code;
                $row->link = $link;
                $row->save();
            } else {
                $g_code = $check->code; //если link повторяется, то показываем старый код
            }

            $short_link = 'https://'. $_SERVER['HTTP_HOST'] . '/' . $g_code; //собираем конечную ссылку

            //параметры из $_POST можно получить с помощью $f3->get('POST'), поддерживается точечная нотация (поправьте, если неправильно называю): параметр "link" можно получить так: 
            $link = $f3->get('POST.link');

            if ( !empty($f3->get('POST')) ) { //Выдаем HTML, только если POST не пустой.

            $f3->set('link', $short_link);
            $f3->set('hits', $check->hits);
            $view = new View;
            echo $view->render('newLink.htm');

            } else { //иначе - редирект на главную
                $f3->$f3->reroute('/');
            }

        }
);

Kua rite! Inaa, he maamaa noa.

Te anga whakamua

He iti noa te mahi hei mahi:

  1. Tikina te tawhā mai i te URL
  2. Tirohia tona aroaro i roto i te pātengi raraunga
  3. Tikina te hono e tika ana mai i te paataka raraunga
  4. Tukuna te kaiwhakamahi
  5. Pūtea!

Ka tuhi tonu matou i te waehere i muri i te huarahi whakamutunga.

$f3->route('GET /@code', //указываем параметр после "@", он попадет в PARAMS
    function($f3) {

        //снова определяем $db
        $db = new DBSQL(
            'mysql:host=localhost;port=3306;dbname=linker',
            'root',
            ''
        );

        $code = $f3->get('PARAMS.code'); //получаем параметр

        $link = new DBSQLMapper($db,'links'); 

        //если получается получить ссылку из БД - получаем, увеличиваем количество переходов и перенаправляем
        if ($link->load(array('code="'.$code.'"', 'link=?'))) {
            $link->hits++;
            $link->save();

            $f3->reroute($link->link);
        } else {
            $f3->reroute('/'); //а если такой ссылки нет - милости просим на главную
        }
    }
);

Kua kite pea koe i tera i roto i te huarahi Hononga hou, a i roto i te huarahi i runga ka whakatauhia te mea ano - i muri i nga mea katoa waehere ka taurite pea ki te "Houhono hou" (kaore e taea, kei roto i te kaihanga nga reta matua anake), engari i te mea kua tautuhia i te tuatahi, ka mahia i te tuatahi.

$f3→ rere()!

Nga mihi mo te panui!
Ka koa ahau mena ka tuhia e koe he korero me te whakatika i ahau mena kei te he.

A, hei mahi kainga, hei tohu ranei mo te mangere o te kaituhi (ahau), ka waiho e au he rarangi o nga mahi ka taea. He pai ake te ako ma te mahi!

  • Ko te tikanga kaore pea tenei, engari i te wa e whakaputa ana $g_waehere tera pea ka pa ano, no reira ka whakaaro ahau kia tuhia he mahi hei tirotiro mo tenei.
  • Ka taea hoki te hanga tatauranga noa me te whakaatu i muri i te huri ki //code/tatauranga
  • Aukati i te hanga hononga ki te ratonga whakapoto hono ake, hanga he rarangi o nga rauemi "tiaki" mai i te whakapoto.
  • Ka tino taunaki ahau ahakoa i roto i tetahi mea iti, ka whakamanahia e koe te whakauru ki te taha o te tūmau, me nga hapa e whakaatuhia ana, kaua koe e whakawhirinaki ki te taapiri i te huanga e hiahiatia ana me te momo = "url" ki te mara whakauru.
    RedComrade

  • Whakaarohia i roto i nga korero...

    Whakapā)

Source: will.com

Tāpiri i te kōrero