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.

55 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?

  30. Wonderful post however I was wanting to know
    if you could write a litte more on this subject? I’d be very thankful if you
    could elaborate a little bit further. Kudos!

  31. Fabulous, what a website it is! This webpage gives useful facts to us, keep it up.

  32. maturevsboy dit :

    Hey just wanted to give you a quick heads up. The words in your post
    seem to be running off the screen in Internet explorer.
    I’m not sure if this is a formatting issue or something to
    do with browser compatibility but I figured I’d post to let
    you know. The layout look great though! Hope you get the issue resolved soon. Kudos

  33. ItsMasum.Com dit :

    Envato Elements Group Buy has improved my creative process!
    Accessing a myriad of resources for design at a reduced
    price is a game changer. This type of collaboration makes high-end design accessible, perfect to any creative task.
    Highly recommend for those looking to take their work to the
    next level without breaking the budget!

  34. porn xxx dit :

    I am really happy to glance at this web site posts which contains lots of valuable facts, thanks for providing
    these information.

  35. Pretty great post. I just stumbled upon your weblog and wished to mention that I have really loved
    surfing around your blog posts. After all I will be subscribing on your feed and I am hoping you write again soon!

  36. Hurrah, that’s what I was seeking for, what a stuff!
    present here at this website, thanks admin of this web
    page.

  37. I do not know if it’s just me or if everyone else experiencing problems
    with your website. It appears like some of the written text on your content are running off the
    screen. Can somebody else please comment and let me know if this is happening to them
    as well? This might be a problem with my internet browser because I’ve had this happen previously.
    Appreciate it

  38. Link exchange is nothing else however it is just placing the other person’s web site link on your
    page at suitable place and other person will also do same
    in support of you.

  39. В этом месяце на актуальное зеркало кракен
    поступает множество эксклюзивных предложений.
    актуальное зеркало кракен Я нашла
    на платформе несколько отличных товаров, которые определенно
    стоят вашего внимания! Во-первых, обратите внимание на раздел Горячие товары.

    Здесь собраны самые популярные и востребованные продукты месяца.

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

  40. porn dit :

    Every weekend i used to go to see this web page, for the reason that i want enjoyment,
    since this this site conations genuinely fastidious funny information too.

  41. Hello, I think your site might be having browser compatibility issues.
    When I look at your blog site in Ie, it looks fine but when opening in Internet Explorer,
    it has some overlapping. I just wanted to give you a quick heads up!
    Other then that, superb blog!

  42. kampus unggul dit :

    Keep up the excellent article, I read few articles on this site and I think that your web blog is real interesting and Power to the People of excellent information.

  43. My spouse and I absolutely love your blog and find nearly all of
    your post’s to be exactly what I’m looking for.

    can you offer guest writers to write content to suit your needs?
    I wouldn’t mind composing a post or elaborating on a few of the subjects you write related to here.
    Again, awesome website!

  44. Great beat ! I would like to apprentice while you amend your
    site, how can i subscribe for a blog website? The account helped me a acceptable deal.
    I had been a little bit acquainted of this your broadcast
    provided bright clear idea

  45. Link exchange is nothing else but it is just placing the other person’s
    blog link on your page at suitable place and other person will also do similar for you.

  46. Die Suche nach dem richtigen Weg, um Gewicht zu verlieren, kann oft frustrierend sein. Eine Möglichkeit, die
    immer beliebter wird, ist die Verwendung von Reduslim,
    einem natürlichen Nahrungsergänzungsmittel, das in Apotheken erhältlich ist.

    Reduslim wird oft als Wundermittel bezeichnet, da es helfen kann, den Stoffwechsel
    zu steigern und somit das Abnehmen zu unterstützen. Durch die Einnahme der Kapseln wird der Körper darin unterstützt, Fett
    schneller zu verbrennen und den Appetit zu zügeln.

    In jeder Apotheke können Sie Reduslim kaufen, um eine effektive Methode
    zur Gewichtsabnahme zu finden. Es ist jedoch wichtig zu beachten, dass Reduslim allein nicht ausreicht, um abzunehmen. Eine ausgewogene Ernährung
    und regelmäßige Bewegung sind ebenso wichtig, um langfristige
    Ergebnisse zu erzielen.

    Also, wenn Sie nach einem natürlichen Weg suchen, um Ihren Gewichtsverlust zu
    unterstützen, besuchen Sie Ihre Apotheke und fragen Sie nach Reduslim.
    Es könnte genau das sein, wonach Sie gesucht haben.

    Here is my web blog reduslim kaufen dm

  47. r9go dit :

    Highly descriptive article, I liked that a lot. Will there be a part 2?

  48. PTS Unggul dit :

    Very impressive website to read

  49. Анализ рекламных стратегий
    Кракена: Как реклама на автобусах увеличивает популярность платформы Рекламная стратегия Кракена, основанная на размещении рекламы на автобусах, оказалась весьма эффективной
    в привлечении новых пользователей на сайт
    кракен даркнет. зеркало kraken market Яркие и запоминающиеся изображения, размещенные на боковинах автобусов,
    привлекли внимание миллионов людей, многие из которых ранее не слышали о платформе.
    Рекламная кампания была нацелена на широкую аудиторию, охватывая как потенциальных покупателей, так и продавцов.
    Изображения на автобусах были тщательно продуманы, чтобы вызвать любопытство и желание узнать больше
    о Кракене. Кампания имела ошеломительный успех, значительно увеличив трафик на сайт
    и повысив узнаваемость бренда.
    Несмотря на некоторые опасения по поводу размещения рекламы
    на автобусах, Кракен проявил профессионализм и креативность в реализации стратегии.
    Изображения были выполнены в соответствии с высочайшими стандартами и соответствовали имиджу бренда.
    Рекламная кампания не только увеличила популярность платформы, но и укрепила
    репутацию Кракена как надежной и заслуживающей
    доверия площадки.

  50. Good info and right to the point. I don’t know if this is truly the best place to ask but do you guys have any thoughts on where to employ some professional writers?
    Thx :) Lista escape roomów

  51. There is certainly a lot to learn about this
    subject. I like all the points you made.

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 :

Combien font 8 multiplié par 4 ?