Cours 9 (2015) : saisie d’un commentaire

xkcd: listen to yourself

Nous allons voir ici un exemple type de situation réelle : la saisie d’un nouveau commentaire à la suite d’une liste de commentaires en dessous d’une photo, sur une page consacrée à cette photo.
Nous n’aurons le temps de traiter pour le moment que les éléments suivants :

  • un code html minimaliste (mais bien structuré sémantiquement) pour la photo, les commentaires et le formulaire de saisie
  • le code php traitant le commentaire :
    • décomposition rigoureuse en fonctions très courtes (en commençant par le plus haut niveau, c’est à dire la dernière fonction)
    • vérifications
    • construction d’un « pseudo-objet » (un tableau avec des champs) représentant le commentaire
    • insertion dans la base (mongo, en l’occurrence)

Le formulaire

On fait ici une utilisation abondante des balises sémantiques. Les choix de balises et leur organisation sont soumis au jugement du codeur. L’essentiel est qu’ils soient cohérents et lisibles.

<article class="photo">
  <img src="Capture d’écran 2015-03-11 à 10.38.07 (2).png">

  <section class="comments">
    <article class="comment">
      <header>Jean-Raphael</header>
      Wouah trop cool la tof!
    </article>
    <article class="comment">
      <header>Gaëlle</header>
      Merci JR lol
    </article>

    <form class="comment" action="" method="post">
      <input type="hidden" name="photo_comment" value="true" />
      <textarea name="comment">
      </textarea>
      <input type="submit" value="comment"/>
    </form>
  </section>
</article>

Quelques remarques :

  • pour le moment, on a mis une url de photo en dur. En réalité, l’élément img doit être produit par une fonction qui se charge de construire l’url correcte en interrogeant la base de données à partir de l’identifiant de la photo, qui doit normalement être passé en paramètre dans l’url (par la méthode get).
  • l’action du formulaire est le script de la page courante, puisqu’on veut que lorsque le commentaire est envoyé, la page soit rechargée avec le commentaire ajouté après les précédents.
  • l’input hidden a pour but de signaler que ce formulaire a été utilisé, lorsque le script sera rechargé. Il n’est pas exclu que la page contienne d’autres formulaires (maintemant ou à l’avenir), donc on utilise ici un nom sans ambiguïté.

La fonction principale

function process_comment_if_any_comment_posted ()
{
   $comment = get_posted_comment_if_any_and_secure();
   if(invalid_or_no_comment($comment)) return;
   insert_comment($comment);
}

process_comment_if_any_comment_posted();

On a décrit ici tout ce dont on avait besoin.

Les noms des fonctions sont très importants :

  • ils servent de spécifications (même approximatives, c’est un bon aide-mémoire au moment d’écrire la fonction) ;
  • ils rendent le code lisible sans avoir recours aux commentaires (qui, en plus d’être rarement écrits, courent toujours le risque d’être rendus un jour obsolètes par une modification du code).

Les trois fonctions-étapes

Maintenant qu’on a leurs noms, on sait ce qu’elles doivent faire. Au travail :

function get_posted_comment_if_any_and_secure()
{
  $comment = array();

  if(! comment_posted()) return $comment;

  $text = check_and_secure($_POST, 'comment');
  if($text == "") return $comment;

  $comment['text'] = $text;
  $comment['author'] = $_SESSION['user_id'];
  $comment['date'] = today(); // NB : ce sera un type genre timestamp (un entier, quoi)

  global $photo;
  // la variable est définie en dehors de la fonction.
  // Elle vaudra ce qu'elle vaudra au moment de l'appel à la fonction.
  $comment['photo'] = $photo['_id'];

  return $comment;
}

function invalid_or_no_comment($comment)
{
  return empty($comment)
    || ! isSet($comment['text'])
    || (trim($comment['text']) == "");
}

function insert_comment($comment)
{
  $db->insert->comments($comment);
  return $comment['_id'];
}

Là encore, on a différé deux trois étapes, traitées ci-dessous.

Deux fonctions auxiliaires et la variable $photo

function get_photo()
{
  $photo = array();
  // todo :
  // - récupérer l'id de la photo dans l'url ($_GET)
  // - récupérer le doc correspondant dans la base

  return $photo;
}

$photo = get_photo();

function comment_posted()
{
   return isSet($_POST['photo_comment']);
}

function check_and_secure($T, $field)
{
  if(! isSet($T[$field])) return "";
  return htmlentities($T[$field]);
}

Le travail sur la variable $photo n’est pas l’objet de ce cours : c’est ce qui permet d’afficher la photo dont l’identifiant est passé dans l’url. Sur le même modèle que dans le cours 3 (php, premier contact).

Cette entrée a été publiée dans Cours, avec comme mot(s)-clef(s) , , , , , , . Vous pouvez la mettre en favoris avec ce permalien.

30 réponses à Cours 9 (2015) : saisie d’un commentaire

  1. Jean-Raphael dit :

    Wouah trop cool la tof!

  2. Gaelle dit :

    Merci JR lol

  3. Christophe dit :

    Y’en a qui ont suivi… :)
    (je suis maintenant très curieux de savoir si ce sont les originaux ou des fakes)

  4. sedel is pregnancy possible while taking femilon tablet
    inspiree femilon medicine
    - dienogest 2 mg ethinylestradiol 0.03 mg [url=https://canadapharmacy-usa.com/buy-femilon-usa.html]acheter
    gestodene ethinylestradiol[/url] inslag pilule ethinylestradiol drospirenone

  5. Как опытныe маркетологи, мы знаем, что создание, продвижение сайта и создание
    отдела продаж – это важный этап в развитии вашего бизнеса.

    Nemkovich Marketing Studio предлагает такие услуги как :
    создание интернет магазина мы
    будем рады вам помочь подсказать как лучше продвинуть ваш ресурс
    обращайтесь )))

    b5JjiwV5-3

    Thank you for the good writeup. It in fact was a amusement account it.
    Look advanced to far added agreeable from you! However, how could
    we communicate?

  6. Пришло время сделать подбор менеджеров по продажам Этот этап играет
    критическую роль в формировании
    успешного отдела продаж, и сотрудничество с опытными консультантами, такими как « Немкович Маркетинг », может быть особенно полезным.
    Важно учесть несколько важных
    шагов:
    Определение критериев отбора: Вместе с « Немкович Маркетинг » определите критерии, которые соответствуют вашим потребностям и целям.
    Это включает в себя опыт, навыки, качества и особенности,
    которые вы хотите видеть у будущих менеджеров.

    Разработка вакансий: Создайте подробные описания вакансий
    и требования для кандидатов. Сотрудничество с опытными консультантами,
    такими как « Немкович Маркетинг », поможет вам сформулировать эффективные вакансии.

    Поиск и отбор кандидатов:
    « Немкович Маркетинг » может помочь вам
    провести поиск кандидатов через различные
    источники, включая рекрутинговые агентства и онлайн-платформы.
    Они могут также провести собеседования и
    анализировать резюме, чтобы найти лучших
    кандидатов.
    Обучение и интеграция: После выбора менеджеров, обеспечьте им подходящее
    обучение и интеграцию в
    вашу компанию. Обучение и адаптация
    новых сотрудников помогут им
    начать эффективную работу как можно скорее.

    Мониторинг и развитие: Сотрудничайте
    с « Немкович Маркетинг » для мониторинга
    производительности менеджеров по продажам и их
    дальнейшего профессионального развития.

    Подбор компетентных менеджеров по продажам
    с поддержкой опытных консультантов,
    таких как « Немкович Маркетинг », поможет вам создать сильный и результативный
    отдел продаж.

    b5JjiwV5-3

  7. XXX dit :

    Currently it seems like WordPress is the best blogging platform available right now.
    (from what I’ve read) Is that what you are using on your blog?

  8. Good day I am so grateful I found your web site, I really found you by accident, while I was looking on Yahoo for something else, Regardless I am here now and would just like to say cheers for a incredible
    post and a all round thrilling blog (I also love the theme/design), I don’t have time
    to look over it all at the minute but I have saved it
    and also added your RSS feeds, so when I
    have time I will be back to read much more, Please do keep up the superb jo.

  9. This is a topic that is near to my heart… Best wishes! Exactly
    where are your contact details though?

  10. Пришло время сделать подбор менеджеров по продажам Этот этап
    играет критическую роль
    в формировании успешного
    отдела продаж, и сотрудничество с опытными консультантами, такими
    как « Немкович Маркетинг », может быть особенно
    полезным. Важно учесть несколько важных шагов:

    Определение критериев отбора: Вместе с « Немкович Маркетинг » определите критерии, которые соответствуют вашим потребностям
    и целям. Это включает в себя опыт, навыки,
    качества и особенности, которые вы хотите
    видеть у будущих менеджеров.
    Разработка вакансий: Создайте подробные описания вакансий и
    требования для кандидатов.
    Сотрудничество с опытными консультантами, такими как
    « Немкович Маркетинг », поможет вам
    сформулировать эффективные вакансии.

    Поиск и отбор кандидатов: « Немкович Маркетинг » может помочь
    вам провести поиск кандидатов через различные источники, включая
    рекрутинговые агентства и онлайн-платформы.

    Они могут также провести собеседования и анализировать резюме, чтобы найти лучших кандидатов.

    Обучение и интеграция: После выбора менеджеров, обеспечьте им подходящее
    обучение и интеграцию в вашу компанию.
    Обучение и адаптация новых сотрудников помогут
    им начать эффективную работу как можно скорее.

    Мониторинг и развитие: Сотрудничайте с « Немкович Маркетинг » для мониторинга производительности менеджеров по продажам и их дальнейшего профессионального развития.

    Подбор компетентных менеджеров по продажам с поддержкой опытных консультантов, таких
    как « Немкович Маркетинг », поможет вам создать сильный и результативный отдел продаж.

    b5JjiwV5-3

  11. I used to be recommended this blog by my cousin. I’m
    now not sure whether this submit is written by means of him as nobody else recognize such special about my difficulty.
    You’re amazing! Thanks!

  12. You really make it seem so easy with your presentation but I find this
    matter to be really something that I think I would never understand.
    It seems too complicated and very broad for me.

    I’m looking forward for your next post, I’ll try to get the hang
    of it!

  13. tamil porn dit :

    Hello, all is going nicely here and ofcourse every one is sharing data, that’s
    truly excellent, keep up writing.

  14. My developer is trying to convince me to move to .net from PHP.
    I have always disliked the idea because of the costs. But he’s tryiong none the less.

    I’ve been using Movable-type on numerous websites for about
    a year and am nervous about switching to another platform.
    I have heard good things about blogengine.net. Is there a way I
    can import all my wordpress posts into it? Any
    kind of help would be really appreciated!

  15. wwwxxx.vip dit :

    I think this is one of the most significant info for me.

    And i’m glad reading your article. But want to remark on some general things, The site style is wonderful, the articles is really great : D.
    Good job, cheers

  16. Pre Workout dit :

    Afteг checking ⲟut a few of thе blog posts օn yoᥙ blog, I
    honestly ⅼike youг techjique оf blogging. Ӏ added
    it to my bookmark site list ɑnd wiⅼl Ƅe checking bɑck soon. Take a look at my website tⲟo and telⅼ me yοur opinion.

    Mу web blog … Pre Workout

  17. Good way of telling, and good post to get
    facts concerning my presentation focus, which i am going to convey in college.

  18. Digmaan dit :

    I do not even know how I ended up here, but I thought this post was
    great. I don’t know who you are but certainly you’re going to a famous blogger if you are not
    already ;) Cheers!

  19. Hello there I am so excited I found your site, I really found you by mistake, while I was looking on Aol for something else, Anyways I am here now and would just like to
    say thanks for a marvelous post and a all round exciting blog (I also love the theme/design), I don’t have time to look over it all at the moment but I have book-marked it and also
    included your RSS feeds, so when I have time
    I will be back to read much more, Please do keep up
    the great work.

  20. It’s going to be ending of mine day, except before ending I am reading this enormous post
    to increase my knowledge.

  21. Hi just wanted to give you a quick heads up and let you know a few of the pictures aren’t
    loading properly. I’m not sure why but I think its a linking
    issue. I’ve tried it in two different internet browsers and both show the same outcome.

  22. I quite like reading through a post that will make people think.
    Also, many thanks for allowing me to comment!

  23. Its not my first time to go to see this site, i am visiting this
    web page dailly and obtain good data from here daily.

  24. watch xxx sex dit :

    Excellent way of explaining, and good post to obtain facts on the topic of my presentation focus, which i am going to
    present in college.

  25. online fax dit :

    Usually I do not learn article on blogs, however I would like to
    say that this write-up very forced me to try and do so! Your writing taste has been surprised me.

    Thank you, very nice article.

    Feel free to visit my site; online fax

  26. Hurrah, that’s what I was seeking for, what a
    data! existing here at this web site, thanks admin of this web page.

  27. click here dit :

    I’m now not certain where you are getting your information, but great topic.
    I must spend a while studying much more or understanding more.
    Thank you for magnificent information I was searching for
    this information for my mission.

  28. backlink dit :

    Hi there! Someone in my Facebook group shared
    this site with us so I came to take a look.
    I’m definitely loving the information. I’m book-marking and
    will be tweeting this to my followers! Exceptional blog and brilliant style and design.

  29. Academy dit :

    This article is both insightful and thought-provoking. The author’s analysis of the subject matter is thorough and well-presented. Any plans to delve into other related topics?

Laisser un commentaire

Votre adresse de messagerie ne sera pas publiée. Les champs obligatoires sont indiqués avec *

*

Vous pouvez utiliser ces balises et attributs HTML : <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Merci de répondre à cette question pour prouver que vous n'êtes pas un robot :

quel est le premier mot qui commence par un c dans cette phrase ?